The nm
command in Linux is used to examine binary files (object files, shared libraries, executables) and display their symbols. It’s a helpful tool for debugging and understanding the internals of compiled programs. This tutorial will cover 10 practical examples of using the nm
command for beginners. Whether you're learning Linux on your local system or working on a remote server like a Windows VPS UK, this guide will help you get started.
1. Basic Usage of nm
The simplest way to use the nm
command is to run it on an object file or executable to display its symbols. For example:
nm /bin/ls
This will list the symbols (functions, variables) from the /bin/ls
executable.
2. Display Symbol Types
The nm
command can display different types of symbols, such as functions and variables. The -f
option provides details about the symbol type:
nm -f /bin/ls
The output shows the symbol type (e.g., T
for text/code section, D
for initialized data).
3. List Only Undefined Symbols
To display only the undefined symbols in an object file, use the -u
option:
nm -u /bin/ls
This lists all symbols that are undefined, which means their definition is missing in the current file.
4. Sort Symbols by Address
You can sort the output of the nm
command by the memory address of the symbols with the -n
option:
nm -n /bin/ls
This will sort the symbols in ascending order based on their memory address.
5. Demangle C++ Symbols
When working with C++ programs, symbol names may appear mangled. Use the -C
option to demangle these symbols:
nm -C /path/to/c++/program
This will display readable C++ function names.
6. Display External Symbols Only
The -g
option will list only external (global) symbols, ignoring local symbols:
nm -g /bin/ls
This is useful for finding globally accessible symbols in shared libraries or executables.
7. List Only Debugging Symbols
Debugging symbols can be displayed using the -a
option. This will include symbols that are typically used during debugging:
nm -a /bin/ls
This is helpful when inspecting debug builds of a program.
8. Display Symbol Size
You can use the --size-sort
option to sort symbols by size, showing which parts of a program take up the most space:
nm --size-sort /bin/ls
This is useful for optimizing programs by identifying large symbols.
9. Include Line Numbers
Use the --line-numbers
option to show which line of code corresponds to each symbol in the output:
nm --line-numbers /path/to/executable
This can help you trace symbols back to the exact line in your source code.
10. Generate Output for a Shared Library
You can analyze shared libraries using nm
. For example, to view the symbols of the libc
shared library:
nm /lib/x86_64-linux-gnu/libc.so.6
This will show the symbols from the libc
library, which is widely used in Linux programs.