How to use the command 'nm' (with examples)
The ’nm’ command is a tool used to list symbol names in object files. It can be useful for debugging and analyzing code, as it provides information about the symbols present in object files. This article will illustrate four use cases of the ’nm’ command.
Use case 1: List global (extern) functions in a file (prefixed with T)
Code:
nm -g path/to/file.o
Motivation:
- This use case is useful when you want to list all the global (extern) functions present in a specific object file.
- It helps in understanding the external functions being used in a compiled code.
Explanation:
- The ‘-g’ option is used to display only global (extern) symbols.
- ‘path/to/file.o’ represents the path to the object file.
Example output:
0000000000000000 T main
0000000000000000 T function1
0000000000000000 T function2
Use case 2: List only undefined symbols in a file
Code:
nm -u path/to/file.o
Motivation:
- This use case is helpful when you want to identify the undefined symbols in a specific object file.
- It allows you to determine the symbols that are referenced but not defined within the file.
Explanation:
- The ‘-u’ option is used to display only undefined symbols.
- ‘path/to/file.o’ represents the path to the object file.
Example output:
U function1
U function2
Use case 3: List all symbols, even debugging symbols
Code:
nm -a path/to/file.o
Motivation:
- This use case is valuable when you need to examine all the symbols in an object file, including debugging symbols.
- It provides a comprehensive view of the symbols present in the file, aiding in code analysis.
Explanation:
- The ‘-a’ option is used to display all symbols, including debugging symbols.
- ‘path/to/file.o’ represents the path to the object file.
Example output:
0000000000000000 T main
0000000000000000 T function1
0000000000000000 T function2
0000000000000000 N debugging_symbol
Use case 4: Demangle C++ symbols (make them readable)
Code:
nm --demangle path/to/file.o
Motivation:
- This use case is specifically applicable to C++ codebases, as it allows for the demangling of C++ symbols.
- It transforms the mangled C++ symbol names into human-readable format, making it easier to understand and analyze the code.
Explanation:
- The ‘–demangle’ option is used to demangle C++ symbols.
- ‘path/to/file.o’ represents the path to the object file.
Example output:
0000000000000000 T main
0000000000000000 T MyClass::function1()
0000000000000000 T MyClass::function2()
Conclusion:
The ’nm’ command is a versatile tool that facilitates symbol analysis in object files. It supports various options to filter and interpret symbol information based on specific requirements. By utilizing the provided use cases, users can extract valuable insights and gain a deeper understanding of their codebases.