gpt4 book ai didi

c++ - 不同文件之间共享全局变量

转载 作者:行者123 更新时间:2023-12-02 18:55:54 25 4
gpt4 key购买 nike

在将其标记为重复之前,我已经尝试过“公共(public) header +外部变量”方法。

来自link :

In A.cpp (or) B.cpp write,

int gVariable = 10;

Remember to write the above definition in only one source file or elselinker will complain of multiple symbols if you write in both thesource files.

And in the common header of A.cpp, B.cpp write,

extern int gVariable;

在这个例子中,当我想将B.cpp包含到A.cpp中(在A.cpp中使用B.cpp函数)时,它不起作用。一个例子是 here

谢谢

最佳答案

您在 test.h 和 shared.h 中使用相同的包含防护

#ifndef SHARED_H //
#define SHARED_H //

extern int testVar;
#endif /*SHARED_H*/

此外,您没有在 test.cpp 中包含 test.h,也没有实际定义 testVar

#include "test.h"

int testVar = 0;

void toOne() {
testVar = 1;
}

https://onlinegdb.com/vCXz53DtJ

KamilCuk 正确地指出以双下划线开头的符号是保留的,所以我也更改了你的包含防护

关于c++ - 不同文件之间共享全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66190085/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com