Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I think the preprocessor handles files one by one and I can't figure out how to do it with includes, so I think it's impossible, but it would be great to hear other's thoughts.

I have in a.cpp:

#define A 1

and I want to use it from 2.cpp.

EDIT: I cant modify first file. So for now i just have copied defines. But question still opened.

like image 773
Yola Avatar asked Jan 11 '13 10:01

Yola


People also ask

Is it possible or would it be possible?

The key difference between "is it possible" and "would it be possible" is that the word "would" changes the sentence by making it hypothetical. When we ask a waiter or waitress at a café, "Is it possible to get more napkins at our table?" we are asking about a real situation that is happening right now.

What does it mean when someone says if possible?

adjective. If it is possible to do something, it can be done. If it is possible to find out where your brother is, we will. Everything is possible if we want it enough. Synonyms: feasible, viable, workable, achievable More Synonyms of possible.

What is the use of possible?

possible and likely mean capable of becoming true or of actually happening. possible is used when something may happen or exist under the proper conditions. It is possible that you may get rich.


2 Answers

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.

like image 157
Luchian Grigore Avatar answered Nov 08 '22 01:11

Luchian Grigore


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.

like image 26
simonc Avatar answered Nov 07 '22 23:11

simonc