Home > Blockchain >  How to Have Preprocessor Statements in Header File Depend on Which C File is Including It
How to Have Preprocessor Statements in Header File Depend on Which C File is Including It

Time:10-22

How can I exclude certain #include statements in my .h file depending on which .cpp is including the .h file?

Example:

main.cpp file

<tell the header.h file that main.cpp is including it>
#include "header.h"

other.cpp file

<tell the header.h file that other.cpp is including it>
#include "header.h"

header.h file

<if called by main.cpp>
#include "some_file_which_fails_when_used_with_OTHER_CPP.h"
<end if>

CodePudding user response:

The typical way to do this is to expect source files to #define a macro prior to including the header:

// the_header.h

#ifndef MY_HEADER_H_INCLUDED
#define MY_HEADER_H_INCLUDED

#ifdef MY_PROJECT_MAIN
// ...
#else
// ...
#endif

#endif

In files using the header's "default" behavior

// some_code.cpp

// Just use the header
#include "the_header.h"

In files using the header's activated behavior:

// main.cpp

// Make sure this is BEFORE the #include
#define MY_PROJECT_MAIN
#include "the_header.h"
  • Related