0

I have a dynamic library lib_funcs.so, written in C. When I link it to a C project (by Code::Blocks) everything is OK, but when I link it to a C++ project and use functions from this library Code::Blocks gives error: undefined reference to 'functions name'.

built1n
  • 1,518
  • 14
  • 25
  • Why are you re-posting the **exact same question!?** –  Jun 18 '13 at 22:47
  • because you didn't give me the answer – Petr Livic Jun 19 '13 at 14:43
  • **Wat?** [What do you think this is?](http://stackoverflow.com/questions/17179797/ubuntuusing-c-so-library-in-c-project#comment24877125_17179797) [And this?](http://stackoverflow.com/questions/17179797/ubuntuusing-c-so-library-in-c-project#comment24877138_17179797) [And this?](http://stackoverflow.com/questions/17179797/ubuntuusing-c-so-library-in-c-project#comment24877182_17179797) –  Jun 19 '13 at 15:59

2 Answers2

4

When you include the header that declares the functions, wrap that inclusion in an extern "C" block.

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

C++ uses name mangling to support function overloading (in which it renames a function to include information about the types of its parameters as well), while C just uses the names that you give the functions. So your C++ code is looking for the functions under their mangled names, not their real names. If you use extern "C" around the declarations of the functions, that will cause the C++ compiler to use C style naming conventions, rather than C++.

Brian Campbell
  • 322,767
  • 57
  • 360
  • 340
0

You need to define the prototypes as extern "C" { prototypes } to prevent name mangling.

unxnut
  • 8,509
  • 3
  • 27
  • 41
  • where i need to define prototypes? – Petr Livic Jun 18 '13 at 22:28
  • In your header file. You can add a statement in the header file as `#ifdef __cplusplus extern C { #endif` towards the beginning before any prototypes are defined and add another one as `#ifdef __cplusplus } #endif` towards the end. – unxnut Jun 18 '13 at 22:39