在 Ubuntu 下“设置 C++ 变量”通常有以下几种常见含义,我分别说明,你可以根据自己的需要选择:
#include <iostream>
int main() {
int a = 10; // 整数变量
double b = 3.14; // 浮点数
std::string s = "hello"; // 字符串
std::cout << a << b << s << std::endl;
return 0;
}
#include <iostream>
int g_count = 0; // 全局变量
void func() {
g_count++;
}
int main() {
func();
std::cout << g_count << std::endl;
}
#include <iostream>
#include <cstdlib>
int main() {
const char* path = std::getenv("PATH");
if (path) {
std::cout << "PATH=" << path << std::endl;
}
return 0;
}
export MY_VAR=123
在 C++ 中用:
std::getenv("MY_VAR");
编辑:
nano ~/.bashrc
添加:
export MY_VAR=123
使生效:
source ~/.bashrc
sudo nano /etc/environment
添加:
MY_VAR=123
g++ main.cpp -DDEBUG -o main
C++ 中:
#ifdef DEBUG
std::cout << "Debug mode" << std::endl;
#endif
set(MY_VAR 10)
add_definitions(-DMY_VAR=${MY_VAR})
如果是“怎么在 Ubuntu 配置 C++ 环境”:
sudo apt update
sudo apt install g++ cmake build-essential
如果你能具体说一下:
我可以给你更精准的示例。