编辑: 正确的函数名称,并添加 #pragma 一次
这是对我的问题的一个非常强大的简化,但如果我这样做:
啊
#pragma once
static int testNumber = 10;
void changeTestNumber();
A.cpp
#pragma once
#include "A.h"
void changeTestNumber()
{
testNumber = 15;
}
溴化氢
#pragma once
#include "A.h"
// some other stuff
B.cpp
#pragma once
#include "B.h"
// some other stuff
主文件
#pragma once
#include "B.h"
#include <iostream>
int main(){
changeTestNumber();
std::cout<<testNumber<<std::endl;
return 0;
}
为什么我在呼叫时没有得到 testNumber = 15?当我使用包含在包含的标头的标头中的函数时,会发生什么?如果我从 int testNumber 中删除 _静态_,我会收到一些关于我的 testNumber 被初始化两次的错误。
那么当我这样做时,我的标题是否编译了两次?
提前致谢!
原文由 remi 发布,翻译遵循 CC BY-SA 4.0 许可协议
除了明显不正确的命名(我认为这只是匆忙创建类似示例的问题,而不是代码中的实际问题),您需要在 .h/ 中将变量声明为
extern
.hpp 文件。你不能有一个extern
变量也是static
因为static
的(其中一个)用途是将变量包含在 a单个.cpp
文件。如果你改变:
在您的
A.h
文件中:然后在您的
A.cpp
文件中执行以下操作:现在继续运行:
请务必修复函数名称!