I need to know that does the #define directive in C++ declares global label? By global I mean visible in every file?
I'm using Visual Studio 2008, (guess if that matters)
No, only in the current translation unit.
I.e. every file which has #define
, or includes a file that has the #define
will see the definition.
Edit, to respond to your comment: to get a define in every file, either put it in a header which gets included everywhere, or use some compiler option to get defines added.
e.g. for gcc one would do
gcc -Dthedefine=itsvalue
Not sure how one specifies such includes in VC++, but I'm sure it's possible somehow.
The #define directive substitutes token-string for all subsequent occurrences of an identifier in the source file. The identifier is replaced only when it forms a token. (See C++ Tokens in the C++ Language Reference.) For instance, identifier is not replaced if it appears in a comment, within a string, or as part of a longer identifier.
It is not global, it is just for the current file/source
define in msdn
Symbol, defined by "#define" is visible from the place of directive to the end of the translation unit (or to the nearest "#undef" for this symbol). For example, if you define something in "file.h" file, this symbol is seen in "file.h" and in every file, which includes "file.h", direct or indirect...
#define
works only in the translation unit it's defined in. With header files shared across translation units, that could be multiple files.
However, to make it truly global you need a Visual Studio extension. The /D command-line option allows you to pass the equivalent of #define
s to the preprocessor, and you can put these in your property page of your project. That's almost "as global as it gets"; for multi-project solutions you can use shared inherited project property sheets.
It'll only be defined in the file you define it or in the files that include that file
Whatever macro you have defined in one file will only be visible in another file if you have included the file with the macro in it, so it's not automatically global. Generally, for this reason macros should be defined in your header files such that you can do a #include "headerFile.h".
A #define
directive will make the definition from that point in time, until compilation completes -- bear in mind that each .cpp counts as a separate compilation unit though.
To define something across source files, it would need to be in a header file that all source files include
You can also setup a visual studio property sheet, which is backed by a .vsprops file, and assign that to the relevant project(s) in your solution.
This would allow you to easily maintain common settings of many types across multiple projects, even if they're in discrete solution files.
http://msdn.microsoft.com/en-us/library/a4xbdz1e%28VS.80%29.aspx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With