Undefined reference to 'dlsym' and 'dl

2020-07-09 09:33发布

问题:

I am compiling using arm-linux-gnueabi-g++ version 4.7.3.

I have the arm-linux-gnueabi libraries installed at location:

/usr/arm-linux-gnueabi/lib, it contains libdl.a, libdl.so, libdl.so.2, and libdl-2.19.so.

libdl.so links to libdl.so.2 which links to libdl-2.19.so.

I am trying to link against the dl library (see command string below), but I always get the undefined reference errors.

arm-linux-gnueabi-g++ -I. -I../ -I../Comms/Linux  -Wall -DLINUX -fpic -o ../../work/MyProgram main.o
-L../../work -L/usr/arm-linux-gnueabi/lib -lComms -lConsole -lUtilities -ldl
../../work/libUtilities.so: undefined reference to `dlsym'
../../work/libUtilities.so: undefined reference to `dlopen'
collect2: error: ld returned 1 exit status

If I compile using g++ 4.8.2 using the following commend then my program compiles, links, and executes fine.

g++ -I. -I../ -I../Comms/Linux  -Wall -DLINUX -fpic -o ../../work/MyProgram main.o
-L../../work -lComms -lConsole -lUtilities -ldl

Obviously it can't find the libdl.so library; I thought that by adding the path to the location of the appropriate library by using the -L flag would fix the problem, but it didn't.

What am I missing with the ARM compiler command?

回答1:

Well, I found the answer, I needed -Wl,--no-as-needed flag before the -ldl. I had run across this flag before I asked the question, but apparently mistyped it because it hadn't worked for me.

I don't understand why the flag is needed, but the code does finish linking now.

A SO user here says that it has to do with recent (2013 as of the user's post) versions of gcc linking to --as-needed.