![](/img/trans.png)
[英]“multiple definition of value” when compiling C program with uninitialized global in g++ but not gcc
[英]multiple definition in g++?
代碼如下:
global.h
#ifndef GLOBAL_H
#define GLOBAL_H
#include <stdio.h>
int test;
void test_fun(void);
#endif
global.c
#include "global.h"
void test_fun()
{
printf("%d\n", test);
}
main.c中
#include "global.h"
int main(void)
{
test_fun();
test = 1;
printf("%d\n", test);
}
Makefile使用gcc編譯器
main: main.o global.o
gcc -o main main.o global.o
main.o: main.c global.h
gcc -c main.c
global.o: global.c global.h
gcc -c global.c
clean:
rm -f global.o main.o main
這很好用。
但是,當我將代碼更改為C ++時,如下所示:
global.h
#ifndef GLOBAL_H
#define GLOBAL_H
#include <iostream>
int test;
void test_fun(void);
#endif
global.cpp
#include "global.h"
void test_fun()
{
cout << test
}
main.cpp中
#include "global.h"
int main(void)
{
test_fun();
test = 1;
std::cout << test;
}
Makefile使用g ++編譯器
main: main.o global.o
g++ -o main main.o global.o
main.o: main.cpp global.h
g++ main.cpp
global.o: global.cpp global.h
g++ global.cpp
clean:
rm -f global.o main.o main
上面的代碼拋出輸出:
global.o:(.bss+0x0): multiple definition of `test'
是什么讓這里有所不同?
...您正在使用不同的編程語言
你進行了int test;
在包含在2個TU中的標題中,因此出錯。 翻譯單元main.c
(或.cpp取決於所使用的編譯器)和global.c
都包含global.h
,這導致兩個目標文件中同一變量的兩個定義,因此鏈接器錯誤。
通過test
作為test_fun的test_fun
,從而避免使用全局。
如果你必須在TU之間共享變量,那么刪除int test;
來自global.h
和main.cpp
int test;
並在global.cpp
做
extern int test;
test_fun();
,因為它是一個全局變量, test
會被初始化為0
,因此當你test_fun();
時,它將被初始化為main
test_fun();
,它應該打印0
然后在設置為1后,它將打印1
。
從語言的角度來看, 它在C和C ++中都是非法的 ,但是為什么它與C編譯器(如GCC)一起工作是因為它們實現了一個共同的擴展,一個遺留的傳統 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.