Is it possible to use #define from other cpp file?

一世执手 提交于 2019-12-05 01:59:27
Luchian Grigore

Defines inside a source file aren't seen by other translation units. Implementation files are compiled separately.

You can either

  • put them in a header and include it
  • use your compiler's options
  • do it the sane way - extern const int A = 1; in an implementation file and declare it when you want to use it extern const int A;.

Of these, I'd say the first option is possibly the worst you can use.

If you want to share a define between two source files, move it to a header file and include that header from both source files.

mydefines.h:

#ifndef MY_DEFINES_H
#define MY_DEFINES_H

#define A (1)
// other defines go here

#endif // MY_DEFINES_H

source1.cpp:

#include "mydefines.h"
// rest of source file

source2.cpp:

#include "mydefines.h"
// rest of source file

You could also specify the define in the compiler command line. This can be fiddly to maintain for cross platform code (which may need different command lines for different compilers) though.

You would need to put your #define in a header file which is then #included by both cpp files.

Like a way - using extern const variables.

For example:

file1.h (where you will use definitions)

extern const int MY_DEF;

#if (MY_DEF == 1)
 //some another definitions
#endif

file2.h (where you will define definitions)

const int MY_DEF = 1

Pro & Con:

(+): you can use some values for defines

(-): ALL definitions must be defined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!