初始化标头 C 中的变量

新手上路,请多包涵

编辑: 正确的函数名称,并添加 #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 许可协议

阅读 358
2 个回答

除了明显不正确的命名(我认为这只是匆忙创建类似示例的问题,而不是代码中的实际问题),您需要在 .h/ 中将变量声明为 extern .hpp 文件。你不能有一个 extern 变量也是 static 因为 static 的(其中一个)用途是将变量包含在 a单个 .cpp 文件。

如果你改变:

 static int testNumber = 10;

在您的 A.h 文件中:

 extern int testNumber;

然后在您的 A.cpp 文件中执行以下操作:

 #include "A.h"
int testNumber = 10;

现在继续运行:

 int main() {
    //changeNumber();
    std::cout << testNumber << std::endl; // prints 10
    changeTestNumber(); // changes to 15
    std::cout << testNumber << std::endl; // prints 15
    std::cin.ignore();
    return 0;
}

请务必修复函数名称!

原文由 Goodies 发布,翻译遵循 CC BY-SA 3.0 许可协议

extern int testNumber;
void changeNumber();

A.cpp

 #include "A.h"

int testNumber = 10;

void changeTestNumber()
{
    testNumber = 15;
}

溴化氢

#include "A.h"
// some other stuff

B.cpp

 #include "B.h"
// some other stuff

主文件

#include "B.h"
#include <iostream>

int main(){

    changeTestNumber();
    std::cout<<testNumber<<std::endl;

    return 0;

}

请这样尝试。

原文由 mustafagonul 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题