Home > Software engineering >  How can I access the define macro in the header file from other files with Conditional Compilation?
How can I access the define macro in the header file from other files with Conditional Compilation?

Time:12-07

I have a macro in a header file:

header.h

#ifndef HEADER_H
#define HEADER_H

#define vulkan

#endif

I want to use this macro with #ifdef from other headers and sources files.

game.h

#ifndef GAME_H
#define GAME_H

#include "header.h"

#ifdef vulkan
//use vulkan api
#else
//use opengl api
#endif

#endif

I also want to use #ifdef in the game.cpp source file, but I can't reach the vulkan macro with #ifdef, neither from the header nor from the source. What is the right way to do this?

EDIT: I am uploading pictures:

header.h

Image

game.h

Image

game.cpp

Image

EDIT 2: minimal reproducible example:

header.h

Image

game.h

Image

game.cpp

Image

main.cpp

Image

EDIT 3: here is the code:

header.h

#ifndef HEADER_H
#define HEADER_H

#define macro

#endif

game.h

#ifndef GAME_H
#define GAME_H

#include "header.h"

class game
{
public:


    #ifdef macro
    int test;
    #else
    int test;
    #endif



    void init();
};

#endif

game.cpp

#include "header.h"
#include "game.h"

void game::init()
{
    #ifdef macro
    int test;
    #else
    int test;
    #endif
}

main.cpp

#include "header.h"
#include "game.h"

int main()
{
    game g;

    g.init();
}

CodePudding user response:

i also want to use #ifdef in game.cpp source ... What is right way ?

This is a right way:

// game.cpp
#include "header.h"

If "header.h" defines a macro, then including it will bring the macro definition to the translation unit.

  •  Tags:  
  • c
  • Related