温馨提示×

如何设Ubuntu C++变量

小樊
49
2026-10-02 10:35:50
栏目: 编程语言

在 Ubuntu 下“设置 C++ 变量”通常分为几种不同场景,下面按常见情况给你说明,你可以对号入座。


一、在 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

二、Ubuntu 环境变量(在终端中给 C++ 程序用)

1️⃣ 临时设置(仅当前终端有效)

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;
}

2️⃣ 永久设置(用户级)

nano ~/.bashrc

在末尾加:

export MY_VAR=123

保存后:

source ~/.bashrc

3️⃣ 系统级(所有用户)

sudo nano /etc/environment

添加:

MY_VAR=123

重启或重新登录生效。


三、编译时通过宏定义变量(g++ -D)

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;
}

四、CMake 中设置变量(常见 C++ 项目)

CMakeLists.txt

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;
}

六、常见误解澄清

  • ❌ “Ubuntu 设置 C++ 变量” ≠ 修改系统变量
  • ✅ 看你是:代码变量 / 环境变量 / 编译变量 / CMake 变量

如果你能具体说一下:

  • 是 环境变量 还是 代码变量
  • 是给 g++ / CMake / VS Code / CLion 用

我可以给你更精确的示例。

0 踩