Linking Error - Use nm to fix
题
I have a linking error which I'm supposed to fix using the nm
command on Unix.
If I have the following linking error: undefined reference to 'program_name'
, and when running nm
on that object file, program_name
symbol is shown as follows in the symbol table: U program_name
.
I know program_name
is undefined, and is defined in another object file which needs to be included with the original object file. My question is: how can I find which object file it is? Is that possible? I have a bunch of object files in a directory and it would be one of them. There's way too many to try all of them.
解决方案
You can do this:
$ nm *.o
Look for program_name
in the output (assuming you have a .o
extension on your object files).
其他提示
Yes. Instead of a U
in the output, you'll find a T
(for "text segment") in the object file that has the symbol defined. Something like this should work (in bash):
for f in *.o; do if (nm "$f" | grep 'T program_name'); then echo "$f" matches; fi; done
Here, I'm looping over all *.o files, and whichever ones have the symbol defined get their filenames printed out.
Try nm -o *.o |grep program_name
and look for the .o file where the symbol has a type of "T" (assuming it's a function name). the -o
option to nm prefixes each line with the filename. Depending on your os, nm may or may not have this option (it might also be -A
) so check your manpages. If it's not there at all, then you'll need to write a shell for loop, something like
for obj in *.obj; do
echo $obj:
nm $obj | grep program_name
done`