Link to C functions in a static library from C ++

I have a static library of functions written in C. Let them say that the header file is called myHeader.h and looks like this:

#ifndef MYHEADER_H #define MYHEADER_H void function1(); void function2(); #endif 

function1 and function2 are not something special. Say they exist in a file called impl1.c, which looks like this:

 #include "myHeader.h" void function1() { // code } void function2() { // more code } 

All the code mentioned so far has been compiled into some static library called libMyLib.a. I would prefer not to modify any code used to create this library. I also have a C ++ header (cppHeader.h) that looks like this:

 #ifndef CPPHEADER_H #define CPPHEADER_H class CppClass { private: double attr1; public: void function3(); }; #endif 

Then cppHeader.cpp looks like this:

 #include "cppHeader.h" #include "myHeader.h" // constructor CppClass::CppClass(){} void CppClass::function3() { function1(); } 

When I try to compile this, I get an undefined error message to function 1 (). I believe that when compiling I connected everything correctly. I'm pretty rusty in my C ++. I'm sure I'm just doing something stupid. Hope my simple sample code illustrates the problem well enough.

Thanks in advance for your help!

+4
source share
2 answers

Another solution (to the sentence originally proposed by Yann) is to surround your heading ā€œCā€:

  #ifdef __cplusplus extern "C" { #endif #ifdef __cplusplus } #endif 

This eliminates the need to remember:

  extern "C" { #include "foo.h" } 

every place you use foo.h

+6
source

Be sure to use:

 extern "C" { #include "myHeader.h" } 

Or else, the C ++ compiler will generate character names that are malformed names.

+4
source

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


All Articles