简体   繁体   中英

Usage of extern keyword in C++

From what I have gathered, the 'extern' keyword in c++ can be used to tell the compiler that a variable is defined in another .cpp file. I was wondering if this definition had to be explicit, or if the definition could be changed via side-effect by a function in the .cpp file where the variable is defined.

ie

//a.h
extern int foo;

//a.cpp
#include <a.h>

int foo=0;
int func(int &foo) // EDIT: oops, forgot the type for the parameter and return statement
{
foo = 10;
return 5;
}
int x = func(foo); // EDIT: changed to match declaration and assigned function to dummy variable

//b.cpp
#include <a.h>

int main()
{
cout << foo;
return 0;
}

Can the program recognize that foo should be 10, or will it be 0? And if the compiler recognizes foo as 0, is there a way I can make it so that it recognizes it as 10? Also, the reason I can't just compile and test this myself is that I'm not sure how to compile when there are multiple files, I'm new =).

EDIT: Thanks for the error pointers, but I guess the main question is still if b.cpp can see if foo is 10 or 0. cheers!

If you correct all the syntax errors and build the whole project, in the file there will be a single integer named 'foo' and it can be accessed for read and write from both sources. Setting it to a value at any place will be read in any other.

It should be 10.

Explanation:

First, the statement

int x=func(foo);

will be called before entering main function, and after

int foo=0;

Second, the foo in func will hide the global foo , so the foo in the func will apply only to the incoming parameter by reference.

Third, your code won't get compiled. Reason 1: you are not using a header from the system, so you need #include "header.h" instead of #include <header.h> . Reason 2: for cout , it is necessary to #include <iostream> and write std::cout , assuming you are not using outdated VC 6.0.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM