1

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!

4

2 回答 2

2

如果您更正了所有语法错误并构建了整个项目,则文件中将有一个名为“foo”的整数,并且可以从两个源访问它以进行读取和写入。在任何地方将其设置为一个值将在任何其他地方读取。

于 2013-07-02T19:39:58.553 回答
2

应该是 10。

解释:

一、声明

int x=func(foo);

将在进入main函数之前和之后调用

int foo=0;

其次,fooinfunc将隐藏 global foo,因此fooinfunc将仅适用于通过引用传入的参数。

第三,您的代码不会被编译。原因 1:您没有使用系统中的标头,因此您需要#include "header.h"代替#include <header.h>. 原因2:对于cout,有必要#include <iostream>std::cout,假设你没有使用过时的VC 6.0。

于 2013-07-02T20:04:58.120 回答