Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
534 views
in Technique[技术] by (71.8m points)

scope - Access extern variable in C++ from another file

I have a global variable in one of the cpp files, where I am assigning a value to it. Now in order to be able to use it in another cpp file, I am declaring it as extern and this file has multiple functions that use it so I am doing this globally. Now the value of this variable can be accessed in one of the functions and not in the other one. Any suggestions except using it in a header file would be good because I wasted 4 days playing with that.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Sorry, I'm ignoring the request for answers suggesting anything other than the use of header files. This is what headers are for, when you use them correctly... Read carefully:

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

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;

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;
}

Now, when you compile and link your project, you must:

  1. Compile each source (.cpp) file into an object file;
  2. Link all object files to create your executable / library / whatever.

Using the syntax I have given above, you should have neither compile nor link errors.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...