从另一个文件访问C++中的extern变量

Ven*_*tel 10 c++ scope global extern

我在其中一个cpp文件中有一个全局变量,我在其中为其赋值.现在为了能够在另一个cpp文件中使用它,我将其声明为,extern并且此文件具有多个使用它的函数,因此我在全局范围内执行此操作.现在,可以在其中一个函数中访问此变量的值,而不是在另一个函数中访问.除了在头文件中使用它之外的任何建议都会很好,因为我浪费了4天玩这个.

pad*_*ddy 37

对不起,我忽略了除了使用头文件之外的其他任何答案的请求.当你正确使用它们时,这就是标题的用途......仔细阅读:

global.h

#ifndef MY_GLOBALS_H
#define MY_GLOBALS_H

// This is a declaration of your variable, which tells the linker this value
// is found elsewhere.  Anyone who wishes to use it must include global.h,
// either directly or indirectly.
extern int myglobalint;

#endif
Run Code Online (Sandbox Code Playgroud)

global.cpp

#include "global.h"

// This is the definition of your variable.  It can only happen in one place.
// You must include global.h so that the compiler matches it to the correct
// one, and doesn't implicitly convert it to static.
int myglobalint = 0;
Run Code Online (Sandbox Code Playgroud)

user.cpp

// Anyone who uses the global value must include the appropriate header.
#include "global.h"

void SomeFunction()
{
    // Now you can access the variable.
    int temp = myglobalint;
}
Run Code Online (Sandbox Code Playgroud)

现在,当您编译和链接项目时,您必须:

  1. 将每个源(.cpp)文件编译为目标文件;
  2. 链接所有目标文件以创建可执行文件/库/任何内容.

使用我上面给出的语法,您既不应该编译也不应该链接错误.

  • +1:谢谢 - 我打算用"正确使用头文件来解决这个问题的唯一正确方法"开始回答.你救了我的努力.我唯一的评论是在`global.cpp`中,我可能会使用一个显式的初始值设定项(即使它是默认的0),只是为了'确定'.我还要提到[C中的什么是`extern`变量](http://stackoverflow.com/questions/1433204/what-are-extern-variables-in-c/)适用于C++,如果有的话很少变化. (2认同)