96

How can I view symbols in a .o file? nm does not work for me. I use g++/linux.

Vadim Kotov
  • 7,766
  • 8
  • 46
  • 61
nakiya
  • 13,523
  • 20
  • 75
  • 116
  • 5
    nm is exactly what you'd use. Can you explain how it doesn't work for you ? – nos Oct 07 '10 at 10:57
  • 1
    It says : `nm: Lib1.o: File format not recognized` – nakiya Oct 07 '10 at 10:59
  • 4
    @nakiya: Run `file Lib1.o` and tell us what the output is. – DarkDust Oct 07 '10 at 11:03
  • I built the object file straight from a header where the implementation was. Does that have anything to do with this? – nakiya Oct 07 '10 at 11:05
  • @DarkDust: How to run an object file? – nakiya Oct 07 '10 at 11:06
  • 4
    @nakiya You can't run an .o file. And if you compile a header file you produce precompiled headers with recent gcc versions, not object files. You should compile .cpp files not header files. – nos Oct 07 '10 at 11:09
  • 1
    @nakiya: You cannot run it, you should really type the text "`file Lib1.o`" in your shell. The tool called `file` tells you the file type of Lib1.o, that is whether it really is an object file. I doubt it. – DarkDust Oct 07 '10 at 11:10
  • Yep. :D. It says it's a precompiled header. I recompiled with implementation in a cpp file. – nakiya Oct 07 '10 at 11:14

5 Answers5

118

Instead of nm, you can use the powerful objdump. See the man page for details. Try objdump -t myfile or objdump -T myfile. With the -C flag you can also demangle C++ names, like nm does.

DarkDust
  • 87,789
  • 19
  • 183
  • 216
15

Have you been using a cross-compiler for another platform? If so, you need to use the respective nm or objdump commmand.

For example, if you have used XXX-YYY-gcc to compile the .o file, you need to use XXX-YYY-nm or XXX-YYY-objdump to process the files.

Schedler
  • 1,353
  • 8
  • 8
6

There is a command to take a look at which functions are included in an object file or library or executable:

nm
Alok Save
  • 196,531
  • 48
  • 417
  • 525
  • 5
    The OP stated directly that he cannot use `nm`. – ivan_pozdeev Mar 13 '16 at 21:31
  • @ivan_pozdeev While that's true, I imagine some people (me at least) come to this question from just searching how to view symbols in object files, and in my case `nm` worked perfectly for my needs, so I think this is a fine answer given the circumstances. – Newbyte Jan 26 '22 at 15:45
6

Just run: nm you_obj_file.o | c++filt

uol3c
  • 539
  • 5
  • 8
2

You can use nm -C .o/lib/exe, for example:

xiongyu@ubuntu:~/tmp/build$ nm -C libfile1.a 

file1.cpp.o:
0000000000000000 T f()
0000000000000000 W int fun<int>(int)

using nm -C it will be more readable, if you just use nm:

xiongyu@ubuntu:~/tmp/build$ nm libfile1.a 

file1.cpp.o:
0000000000000000 T _Z1fv
0000000000000000 W _Z3funIiET_S0_

as we see it's not so readable.

Below is what my file1.cpp like:

xiongyu@ubuntu:~/tmp/build$ vi ../file1.cpp 
#include "head.h"
void f()  {
     int i = fun<int>(42);
}
Jayhello
  • 4,975
  • 3
  • 44
  • 53