“价值的多重定义"指的是“价值的多重定义".在g ++中使用未初始化的全局变量编译C程序时,但在gcc中编译时 [英] "multiple definition of value" when compiling C program with uninitialized global in g++ but not gcc
问题描述
我试图了解头文件中extern和global变量声明的用法,所以我想出了以下用C语言编写的测试程序.
I'm trying to understand the usage of extern and global variable declaration in header files so I came up with the following test program written in C.
main.c文件
//main.c
#include "global.h"
#include <stdio.h>
int nExternValue = 6;
int main(int argc, char* argv[])
{
printf("%d \n", nValue);
printf("%d \n", nExternValue);
AddToValue();
printf("%d \n", nValue);
printf("%d \n", nExternValue);
}
global.h文件
The global.h file
#ifndef _GLOBAL_H
#define _GLOBAL_H
//WRONG! do not declare a variable here
int nValue;
//OK! extern variable makes it a global accessable variable
extern int nExternValue;
//OK! function prototype can be placed in h file
int AddToValue();
#endif
和一个实现AddToValue函数的AddValue.c文件.
and a AddValue.c file which implements the AddToValue function.
#include "global.h"
int AddToValue() {
nValue++;
nExternValue++;
}
我使用gcc编译了应用,并运行了它:
I compiled the app using gcc, AND ran it:
$ gcc main.c AddValue.c -o test
$./test
0
6
1
7
我使用g ++编译了该应用程序,并收到以下链接器错误:
I complied the app using g++ and got the following linker error:
$ g++ main.c AddValue.c -o test
/tmp/ccFyGDYM.o:(.bss+0x0): multiple definition of `nValue'
/tmp/cc3ixXdu.o:(.bss+0x0): first defined here
collect2: ld returned 1 exit status
为什么gcc链接器不产生错误?我虽然会多次声明nValue变量,但这会产生错误!
Why doesn't the gcc linker produce an error? I though the nValue variable would be declared multiple times and that would produce an error!
$ gcc --version
gcc (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3
Copyright (C) 2011 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
$ g++ --version
g++ (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3
Copyright (C) 2011 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
推荐答案
C和C ++是不同的语言.例如,以上程序是有效的C程序,但格式不正确.您违反了C ++的一个定义规则. C中没有相应的规则.
C and C++ are different languages. Case in point, the above program is a valid C program but in ill-formed C++ program. You have violated C++'s one definition rule. There is no corresponding rule in C.
使用gcc进行编译时,您正在将以上文本编译为C程序.使用g ++进行编译时,您将上述文本作为C ++程序进行编译.
When compiling with gcc, you are compiling the above text as a C program. When compiling with g++, you are compiling the above text as a C++ program.
这篇关于“价值的多重定义"指的是“价值的多重定义".在g ++中使用未初始化的全局变量编译C程序时,但在gcc中编译时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!