How do you link a C ++ static library with a C program?

I have the following C ++ program:

client.h

#ifndef Client_Client_h #define Client_Client_h #include "Client.h" class Client { public: void f1(); void f2(); }; #endif 

client.cpp

 #include <iostream> #include <stdlib.h> using namespace std; #include "Client.h" void Client::f1(){ cout << "Client.f1()" << endl; } void Client::f2() { cout << "Client.f2()" << endl; } 

The compilation above in Xcode 4.3 gives me a static library file:

 libClient.a 

Separately, I have main.c

 #include <stdio.h> // //using namespace std; int main(){ // how do I do something like: Client c; c.f1(); c.f2(); // and actually get output ? printf("hello\n"); return 0; } 

What steps do I need to take to call f1 () and f2 ()? How to use GCC to correctly link to a static library?

So far I have tried:

 gcc -lClient.a main.c 

which gives me:

 ld: library not found for -lClient.a collect2: ld returned 1 exit status 
+4
source share
1 answer

This will not work, or at least not be portable. The only really really obvious thing is to make your C ++ program so that you can access these functions.

You cannot "use" C ++ code from C code for obvious reasons. You don't have access to object-oriented functions, so a ton of things won't work: constructors, destructors, move / copy semantics, and virtual inheritance are probably the biggest things you will miss. (This is right: you cannot correctly create or destroy objects if they do not have trivial constructors and destructors.)

You will also encounter communication problems: C ++ function names are crippled in a mess, including their parameter types and return types and classes, which will look like __1cGstrcpy6Fpcpkc_0_ . It would be technically possible to declare distorted function names in C to use them, or use dlsym to get a pointer to them, but that is just plain stupid. Do not do this.

If you need to create a function in C ++ that must be called from C, you can specify it as extern "C" , and its name will not be distorted, and it will be accessible from C, and he will be able to use the capabilities of C ++ :

 extern "C" void Foo() { std::string hello = "Hello world!"; std::cout << hello << std::endl; } 

Then you need to declare it on the C side of your program as follows:

 void Foo(); 

And you can call it.

You can wrap all your C ++ calls that you want to open for your C program in extern "C" functions, and return a pointer to your type and deal with it this way, but it is very annoying very quickly, you really should just use c ++.

Regarding the connection with the static library, in Xcode go to the settings of your project, select the target, go to the "Phase assembly" tab, expand the "Link binary files to libraries" section and omit the .a file.

+8
source

Source: https://habr.com/ru/post/1498532/


All Articles