gpt4 book ai didi

c++ - "multiple definition of value"在 g++ 而非 gcc 中编译具有未初始化全局的 C 程序时

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:24:18 35 4
gpt4 key购买 nike

我试图了解头文件中 extern 和全局变量声明的用法,因此我想出了以下用 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 文件

#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 文件。

#include "global.h"

int AddToValue() {
nValue++;
nExternValue++;
}

我使用 gcc 编译了应用程序,并运行了它:

$ gcc main.c AddValue.c -o test
$./test
0
6
1
7

我使用 g++ 编译了该应用程序并收到以下链接器错误:

$ 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 变量会被声明多次并且会产生错误!

$ 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中没有对应的规则。

当使用 gcc 编译时,您将上述文本编译为 C 程序。当使用 g++ 编译时,您正在将上述文本编译为 C++ 程序。

关于c++ - "multiple definition of value"在 g++ 而非 gcc 中编译具有未初始化全局的 C 程序时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13596577/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com