in C or C++, how can I prevent previous #define in a header file from affecting another header file later included?

Viewed 144

I think there may be no way of avoiding this but to change function/macro name, but I ask here just in case.

I have met a strange situation.

I'm trying (just started) to modify a program A (targeted for a dynamic library) so that the program uses a function in program B (this is not relevant for this question, but Program A is a simulator for an accelerator based on multi2sim written by my colleague, and program B is qemu, the famous CPU/machine emulator).

A file driverA.cc in program A looks like this:

#include "includeA.h"

#ifdef USED_IN_QEMU
#include "includeB.h"
#endif

// some code...

includeA.h has a macro like this:

#define set_pc(x) \
  do { p->check_pc_alignment(x); \
       npc = sext_xlen(x); \
     } while(0)

But includeB.h has this code:

static inline void cpu_set_pc(CPUState *cpu, vaddr addr)
{
    CPUClass *cc = CPU_GET_CLASS(cpu);
                 
    cc->set_pc(cpu, addr);
} 

The compiler complains that set_pc() is supposed to take only one argument according to includeA.h, but set_pc() in includeB.h takes two arguments. I know it's just the same name but different functions or macros, but there arose conflicts between the include files. The compiler doesn't know they belong to different worlds.

How can I avoid this kind of compile error?

1 Answers

Switch the order of the includes:

#ifdef USED_IN_QEMU
#include "includeB.h"
#endif

#include "includeA.h"

That way the macro in includeA.h doesn't affect anything in includeB.h.

Related