Reputation: 35
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.
i.e.
//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!
Upvotes: 1
Views: 3274
Reputation: 24850
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.
Upvotes: 2
Reputation: 17163
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.
Upvotes: 2