I’ve created a dynamic networking library in C. When I try to link it in my C++ program I get an undefined reference the first time I call one of my functions in the library. What I can’t understand is that I created a little test program in C that uses the library and it links just fine.
Could someone help with my problem? Here are the steps I’ve taken to create my library and link it.
Library creation:
- Code my library
- Compile with the line: gcc -c -fPIC -g -Wall ./libnet.c
- Link my library object file and create the shared object file with the line: gcc -shared -o libnet.so -g -Wall ./libnet.o
Move my library to the appropriate folders and set LD_LIBRARY_PATH:
- I copy my library to two directories. One directory is the test C program that links properly and one is the C++ program that doesn’t link properly.
- I set the environment variable LD_LIBRARY_PATH to both the directories that use the library
Compile and link my program:
- Code my program
- Compile all my .cpp files with the line: g++ -c -g -Wall ./
- Link together all my object files and the shared library to create my program with the line: g++ -o -g -Wall -L./ -lnet
Here is the make file that I use. Maybe I have something wrong in here?
PPFLAGS = -g -Wall
TARGET = msgfrwdserver
OBJS = msgfrwdserver.o
msgfrwdhelper.o msgfrwd.o climsgfrwd.oLIBS = libnet.so
CPPLP =
-L/usr/home/chris/development/legends/servers/monitor
-L/usr/home/chris/development/legends/servers/msgfrwdCPPFILES = ./msgfrwdserver.cpp
./msgfrwdhelper.cpp
./classes/msgfrwd.cpp
./classes/climsgfrwd.cppCPPIP = -I./classes
-I/usr/home/chris/development/legends/libnetall: ${OBJS} ${TARGET}
${TARGET}: ${OBJS} ${LIBS}
g++ -o
${TARGET} ${PPFLAGS} -L./ -lnet
${CPPIP} ${OBJS}msgfrwdserver.o: ./msgfrwdserver.cpp
g++ -c ${PPFLAGS} ${CPPIP}
./msgfrwdserver.cppmsgfrwdhelper.o:
./msgfrwdhelper.cppg++ -c ${PPFLAGS}
./msgfrwdhelper.cppmsgfrwd.o:
./classes/msgfrwd.cppg++ -c
${PPFLAGS} ./classes/msgfrwd.cppclimsgfrwd.o: ./classes/climsgfrwd.cpp
g++ -c ${PPFLAGS} ${CPPIP}
./classes/climsgfrwd.cppclean: rm
-rf ${TARGET} *.o *~ .core ./classes/~
I really have no idea what the problem could be. Any help would be much appreciated. Do I have to do something differently to get a C library to work with a C++ program?
Sorry that the make file is messy. I didn’t exactly translate well when I tried to block quote it or say it was a code sample.
C library functions must have en extern “C” definition in order to call them from C++ to turn of name-mangeling.
With the extern , the the Microsoft C++ compiler will look for the symbol “_test“, otherwise it will look for “?test@@YAHXZ” (The C++ name-mangeled version of int test() )