在 Ubuntu 下“设置 C++ 变量”通常分为几种不同场景,下面按常见情况给你说明,你可以对号入座。
#include <iostream>
int main() {
int a = 10; // 整型变量
double b = 3.14; // 浮点型
std::string s = "hello"; // 字符串
std::cout << a << std::endl;
return 0;
}
编译运行:
g++ test.cpp -o test
./test
export MY_VAR=123
在 C++ 中读取:
#include <iostream>
#include <cstdlib>
int main() {
const char* v = std::getenv("MY_VAR");
if (v) std::cout << v << std::endl;
}
nano ~/.bashrc
在末尾加:
export MY_VAR=123
保存后:
source ~/.bashrc
sudo nano /etc/environment
添加:
MY_VAR=123
重启或重新登录生效。
g++ test.cpp -DDEBUG -DMAX=100 -o test
C++ 中使用:
#include <iostream>
int main() {
#ifdef DEBUG
std::cout << "debug mode" << std::endl;
#endif
std::cout << MAX << std::endl;
}
set(MY_VAR "hello")
add_definitions(-DMY_VAR="${MY_VAR}")
C++ 中:
std::cout << MY_VAR << std::endl;
#include <iostream>
int globalVar = 100;
int main() {
static int count = 0;
count++;
std::cout << count << std::endl;
}
如果你能具体说一下:
我可以给你更精确的示例。