The C language uses defined constants to represent consistent values across platforms. For example, the PATH_MAX
value might be 260 on one system and 4096 on another. It’s not important to know the specific value, just use the defined constant and your code builds and runs on various systems (hopefully).
If you’re a nerd who enjoys code spelunking, you might want to know the specific value of a defined constant. I’ve done so many times. For example, in a previous blog post I wrote code to locate and output the PATH_MAX
value. I’ve written specific programs that just output a library’s version number. Call me crazy.
Well, I am crazy because a simple shortcut exists to output the value of any defined constant. All you need to know is which header file defines the constant and then use this format at the command prompt:
cpp -include header.h -dM /dev/null | grep '#define DEFCONST'
The cpp program is the C preprocessor. It’s called by the compiler to prepare the source code file. Using the above format, substitute header.h
with the proper header file and DEFCONST
with the defined constant name to view specific #define
directives in the header file.
Here’s an example:
$ cpp -include limits.h -dM /dev/null | grep '#define PATH_MAX'
#define PATH_MAX 4096
The PATH_MAX
defined constant is set to the value 4096 on this system. (It’s the maximum string size for a pathname.)
Here’s how the command line works:
cpp is the C preprocessor.
-include directs the compiler to include the named header file.
limits.h is the header filename. If you’re scanning a header file in a subdirectory, such as sys/net/ethernet.h
, specify the pathname.
-dM directs the compiler to generate a list of #define directives in the code.
/dev/null is the empty file, the “road to nowhere.” The cpp program requires a filename argument, though it still examines the header file specified.
The output from this command so far generates a list of all #define directives in the header file. To find a specific one, you pipe the output through the grep utility:
| grep “#define PATH_MAX”
The match string must include the #define directive. Otherwise, the output includes all references to the defined constant, which may be more than needed.
While this trick is great, and I use it a lot, it doesn’t help in your code when the defined constant is unavailable. Refer to this post for information on how to use #ifdef to test for a definition. You can use the precompiler directives to generate a different program based on whether the constant is available or not.