Search code examples
cmacrosincludec-preprocessorheader-files

Include header file only if it is available in C?


I want to add logic for pthread into a small profiling library I'm writing for C. However, I only want to execute the logic relevant to pthread if pthread is available.

Is there a programmatic way to do this using preprocessor directives?

I imagine it would look something like:

#ifdef pthread_h
#include <pthread.h>
#endif

. . .


#ifdef pthread_h
// pthread specific logic here
#endif

But the part I'm uncertain about and don't know what to do with is

#ifdef pthread_h

If I haven't included pthread.h yet, pthread_h isn't available. Right?

Is there a way to include a header file only if it's available? Perhaps I could achieve the result I'm looking for that way.


My desired result is to include information about the current Thread ID in the profiling data, but only if the library has pthread available to call pthread_self().


Solution

  • "Is there a way to include a header file only if it's available? Perhaps I could achieve the result I'm looking for that way."

    Yes. You can use i.e. the __has_include macro, if your compiler supports it:

    #if defined __has_include
    #  if __has_include (<pthread.h>)
    #    include <pthread.h>
    #  endif
    #endif
    
    ...
    
    #if defined __has_include
    #  if __has_include (<pthread.h>)
    #    // pthread specific logic here
    #  endif
    #endif
    

    Side Note:

    • "... if pthread has actually been linked at compile time."

    The linking process is not done at compile time. It comes after the compilation. And the C preprocessor does its work even before the compilation.