Search code examples
cgccmingwc-preprocessorlinker-flags

Is it possible for preprocessor to check if a linker option is used?


I have a timer program which uses clock_gettime. This requires -lpthread option to compile successfully or else it gets undefined reference to 'clock_gettime' error.

As so far I explored that we can generate preprocessor warning messages with #warning and check if the include is present by #if __has_include("<pthread.h>"). But checking those does not really check if clock_gettime function is defined.

Just curious if I can make a custom message to warn people at compile time or preprocessing time who compiled without it to include -lpthread option.

I am using MinGW on Windows.


Solution

  • I have a timer program which uses clock_gettime. This requires -lpthread option to compile successfully or else it gets undefined reference to clock_gettime error.

    clock_gettime requires -lrt, see man clock_gettime. -lpthread just happens to depend on that library.

    -lpthread linker option should never be used because it is not sufficient. The correct way to compile and link multi-threaded applications is to use -pthread compiler and linker option. The compiler option defines the required macros, the linker option links the correct library.

    Just curious if I can make a custom message to warn people at compile time or preprocessing time who compiled without it to include -lpthread option.

    -lrt is a linker option. When object files are compiled separately from linking, the linker options are not a part of the compiler command line and hence aren't available at that stage. There is link-time code generation, however, the compilers don't normally export linker options as macros for the code being compiled to inspect.