1

I am trying to use a library called libRNA. I installed it following the instructions on their website.

If I am calling functions of that library in a main.c file, I can compile it using the gcc compiler and it works like charm:

 gcc -g -Wall -fopenmp -std=c++11 test.c -lRNA -lm -o test.out

But if we rename the file to main.cpp and compiling it with gcc

gcc -g -Wall -fopenmp -std=c++11 test.cpp -lRNA -lm -lstdc++ -o test.out

none of the referenced functions of the RNA lib can be found:

/home/joachim/tutorial_libs/test.cpp:18: undefined reference to `vrna_alloc(unsigned int)'
/home/joachim/tutorial_libs/test.cpp:19: undefined reference to `vrna_alloc(unsigned int)'
etc...

I read that gcc treats .cpp files as c++ files and .c files as c files. Does this mean I can not link the library with a c++ file? But how can it then be achieved to use the library within a c++ application? (needless to say that using g++ would not change the situation.)

I am thankful for any hint or suggestion for additional reading! Thanks in advance!

newandlost
  • 935
  • 2
  • 10
  • 21
  • C++ needs `extern "C"` to make the function names compatible with C. Differences in names (keyword: "name mangling") confuse the linker. – Ben Voigt Jan 14 '18 at 02:57
  • In the duplicate, the particular answer you need is https://stackoverflow.com/a/12574420/673730 – Ben Voigt Jan 14 '18 at 02:58
  • Oh man thanks a lot! You don't know how long time I have been trying to get this to work! So basically I wrap the headers of the library with extern "C" {}? – newandlost Jan 14 '18 at 03:02
  • Yeah, doing `extern "C" {` before a header include and `}` after (on separate lines, because `#include` needs a whole line to itself) is usually all you need. Actually, most libraries will put that inside the header file (protected by `#if __cplusplus`) to make it totally painless. But I guess your library doesn't. – Ben Voigt Jan 14 '18 at 03:06
  • I see that the answer given there fits my question, but my question is much for specific then the question that was asked there. Most of the answers do not fit my question or problem at hand. Is it possible to directly link to the answer of Luchian Grigore in the "duplicate" link? – newandlost Jan 14 '18 at 03:09

0 Answers0