C++ 在头文件定义全局变量

Posted by agentd on 02-17,2022

编程时常常需要把常量定义在一个地方,方便管理。

在 C++ 中可以在头文件声明并定义 static const 变量作为全局变量,这样只用 include 对应头文件就可以直接使用头文件里定义的变量了。

头文件 constants.h

#ifndef __DEMO_CONSTANTS_H__
#define __DEMO_CONSTANTS_H__
#include <string>

namespace demo {
namespace constants {
    static const std::string business = "feed";
    static const std::string debugLogPath = "./debug_log/";
}
}
#endif

使用头文件中定义的全局变量

business.cpp

#include 'constants.h'
namespace demo {
namespace business {
int main() {
    std::cout << demo::constants::business;
    return 0;
}
}
}