简体   繁体   中英

How to define a file-scope symbol in C++

In C#, the #define directive defines a symbol, for example, the following line defines a symbol "DEBUG":

#define DEBUG

the scope of this symbol is the file in which it is defined.

In C++, a pre-processing symbol (/D "DEBUG") can be defined to get the same effect. But /D is a project-wide setting switch.

My question is, how to define a symbol that is local to a file in C++?

#define in C and C++ is available, but it does not create a symbol, it creates a pre-processor macro, which is essentially a text replacement operation which takes place before the compiler even sees the source file.

The usual way to create a file-local symbol in a C++ file is to use an anonymous namespace, eg

namespace 
{
    const int SOME_LOCAL_INT = 3;
    const std::string SOME_LOCAL_STRING("Blah");
}

The use of an anonymous namespace ensures that the symbol is not visible outside of the compilation unit in which it is defined. Note however that if you define an anonymous namespace inside a header file, a copy of the symbols contained within will be accessible inside all C++ files which include that header file, so it is best to put the anonymous namespace inside a.cpp file to ensure that they are indeed local.

If you want to necessarily use #define in a header for symbol to be local in that header, then use as below:

//file.h
#define DEBUG
//... code
#undef DEBUG // clearing the symbol

#undef will undefined the previously defined DEBUG . So if you #include this file.h anywhere, it won't have any effect of DEBUG as it's just local to file.h .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM