luffy
luffy

Reputation: 23

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

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();
}

Upvotes: 0

Views: 1244

Answers (1)

eerorika
eerorika

Reputation: 238321

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.

Upvotes: 1

Related Questions