0

im trying to compile some c++ code that uses a stub library i wrote. The library is written in C and has a header and a few functions that do nothing. In my makefile i compile the library with

gcc -Wall -Werror -c myLib.c -o myLib.o
gcc -shared -nostartfiles -Wl,-soname,libmyLib.so -o libmyLib.so myLib.o

The library seems to build fine, running ld -lmyLib --verbose finds the library and shows all the functions. Note: is does give a warning:

cannot find entry symbol _start; not setting start address

Then in my other code I compile and link seperately. I compile with

g++ -Wall -Werror -c foo.o foo.cpp -lmyLib

This compiles fine, foo.cpp contains #include<myLib.h> and myLib.h is in /usr/include/

When i try to link it all together with

g++ -o mainProg *.o -lmyLib

i get the errors "undefined reference to (functions in mylib)"

I have tried to figure this out for a few days but have had no luck. Is there something silly I am missing?

Thanks and let me know if theres any more info I can give.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
ben23f
  • 47
  • 5
  • 4
    Are your C functions declared extern "C" in the C++ header? – Anon Mail Feb 12 '18 at 20:49
  • `g++ -Wall -Werror -c foo.o foo.cpp -lmyLib` FYI the `-lmyLib` does nothing there – Lightness Races in Orbit Feb 12 '18 at 20:54
  • I don't know what you mean by extern C, are you talking about in the library header myLib.h? Or in foo.h? – ben23f Feb 12 '18 at 21:18
  • See [Language linkage](http://en.cppreference.com/w/cpp/language/language_linkage), for C functions used by C++ code, say something like `extern "C" { void c_function_1(args); int c_function_2(other args); }` – Olaf Dietsche Feb 12 '18 at 21:24
  • @ben23f The library header will need to declare your C functions as extern "C", otherwise the C++ compiler will mangle their names. A C library will not have its names mangled. – Anon Mail Feb 12 '18 at 21:31
  • Don't use `ld` directly as you value your sanity. Use `gcc` or `g++` (depending on which you use to create the object files). The compilers add all sorts of extra options to the `ld` command. Run with `-v` (`g++ -v -Wall -Werror -c foo.o foo.cpp -lmyLib` for example) to see what really gets run for you. The `_start` symbol is normally defined in an object file with a name such as `crt0.o`. See also [Undefined references in C++](https://stackoverflow.com/questions/12573816/what-is-an-undefined-reference-unresolved-external-symbol-error-and-how-do-i-fix). – Jonathan Leffler Feb 13 '18 at 01:28
  • And if you think you've got your startup code somewhere, you will need to tell `ld` to look for your start symbol instead of its default `_start`. – Jonathan Leffler Feb 13 '18 at 01:31
  • Hi @OlafDietsche thanks for the link. Wrapping the header file in extern C solved it for me. Interesting lesson learned about name mangling! – ben23f Feb 27 '18 at 09:04

0 Answers0