0

I'm trying to compile some code that use a function implemented in a static library named staticlib.a. I also have the header named staticlib.h which contain the declaration of that function. My main, that is contained in the main.c file wich include staticlib.h, only calls that function and no else. So I compile with gcc main.c staticlib.a and everything work fine. I need some feature of c++ but if I properly change main.c in main.cpp and compile same way gcc main.cpp staticlib.a an undefined reference to my function occured. How can I make this works? And why this problem occurred? I cannot really find an explanation in any site i visited... Thank you for all trhe answers.

3
  • To the OP, please accept some answers, it's clear you don't understand the operations of the stackoverflow site Commented Oct 18, 2012 at 14:54
  • 1
    well, till now i have made 3 question on stackoverflow site, and till now there isn't be any answear that have totally resolved my problem... in this question i have recived the right answear, and now i will accept it... Commented Oct 18, 2012 at 15:04
  • This question is similar to: How can I add a (.a) static library to a C++ program?. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented Jan 4 at 1:31

2 Answers 2

1

you have to define the function in the library as a 'C' function, not a C++ function - do this in your main.cpp

extern "C" { #include "staticlib.h" } 
Sign up to request clarification or add additional context in comments.

Comments

1

C and C++ compile differently, C++ uses name mangling (embedding C++ type information in the object file). To stop this behaviour so that you can link to C code from C++, you can use the extern C syntax in C++ when including the C header file.

Please see here http://www.cplusplus.com/forum/general/1143/

Comments