yingyong.c
int yueqiu;
void sub_fun(void)
{
yueqiu = 2;
printf("sub yueqiu = %d\n", yueqiu);
}
main.c
int yueqiu;
void sub_fun(void);
int main(int argc, char *argv[])
{
yueqiu = 1;
printf("main yueqiu = %d\n", yueqiu);
sub_fun();
return 0;
}
打印结果:
main yueqiu = 1
sub yueqiu = 2
C和C++中是不一样的
C中可能会被当做声明,而C++中肯定是定义 不同的编译器效果不一样?
Object declaration at file scope
Note
In C++, a declaration of an object at file scope without a
storage class specifier is a definition of that object
with external linkage. If the definition does not have an
initializer, the object has initial value 0. (As in C, an
object declared in a C++ program must be defined exactly
once.)
In C, a declaration of an object at file scope without a
storage class specifier and without an initializer is a
tentative definition, which may appear more than once in a
translation unit.
Example
int a; /* (1) */
int a = 10; /* (2) */
In C, (1) is a tentative definition. Since (2) is
unequivocally a definition, C treats (1) as a mere
declaration.
In C++, both (1) and (2) are definitions. In the
presence of (1), (2) is a duplicate definition, and
therefore an error
另外,<<深度探索对象模型>>page197
因为int a;没有明确的初始化操作,所以a被视为一个"临时性的定义",可以在程序中发生多次
那些实例会被连接器折叠起来,只留一个单独的实体
若是 int yueqiu = 3; 即为一个实体,若在另一个文件中又 int yueqiu = 4; 则构成重复定义,同理包含同一个头文件(int yueqiu = 5),也会构成重复定义
c++多个文件中如何共用一个全局变量