Avatar ·

如何使用extern在C++文件间共享变量?

你好!我开始学习C++,并尝试将程序拆分成多个文件。我有三个文件:main.cpp、functions.cpp和functions.h。在functions.h中,我声明了一个全局变量int global_counter = 0;和几个函数。在functions.cpp中,我定义了这些函数,它们修改global_counter。在main.cpp中,我包含functions.h并尝试使用global_counter,但编译器报错“multiple definition of `global_counter`”。我听说过extern关键字,但不完全理解如何正确使用它。你能用一个简单的例子解释一下吗?以下是我当前的代码: // functions.h #ifndef FUNCTIONS_H #define FUNCTIONS_H int global_counter = 0; void increment(); void print_counter(); #endif // functions.cpp #include "functions.h" #include void increment() { global_counter++; } void print_counter() { std::cout << global_counter; } // main.cpp #include "functions.h" int main() { increment(); print_counter();