C/C++多重定義例項
阿新 • • 發佈:2018-12-18
main.cpp
#include <stdio.h>
#include <stdlib.h>
#include "gh.h"
int main()
{
printf("%d \n",a);
return 0;
}
fun.cpp
#include <stdio.h>
#include "./gh.h"
void fun2()
{
printf("a2:%d \n",a);
}
gh.h
#ifndef GH_H_
#define GH_H_
int a=0;
int b=1;
#endif
(只編譯)沒錯誤,但這該死的水印.
連結階段出現錯誤,重複定義.
使用objdump -t 檢視 *.o檔案內的符號如下:
main.o: 檔案格式 elf64-x86-64 SYMBOL TABLE: 0000000000000000 l df *ABS* 0000000000000000 main.cpp 0000000000000000 l d .text 0000000000000000 .text 0000000000000000 l d .data 0000000000000000 .data 0000000000000000 l d .bss 0000000000000000 .bss 0000000000000000 l d .rodata 0000000000000000 .rodata 0000000000000000 l d .note.GNU-stack 0000000000000000 .note.GNU-stack 0000000000000000 l d .eh_frame 0000000000000000 .eh_frame 0000000000000000 l d .comment 0000000000000000 .comment 0000000000000000 g O .bss 0000000000000004 a 0000000000000000 g O .data 0000000000000004 b 0000000000000000 g F .text 0000000000000024 main 0000000000000000 *UND* 0000000000000000 _GLOBAL_OFFSET_TABLE_ 0000000000000000 *UND* 0000000000000000 printf ;關鍵點注意a和b的第二項均為 g(global) un.o: 檔案格式 elf64-x86-64 SYMBOL TABLE: 0000000000000000 l df *ABS* 0000000000000000 fun.cpp 0000000000000000 l d .text 0000000000000000 .text 0000000000000000 l d .data 0000000000000000 .data 0000000000000000 l d .bss 0000000000000000 .bss 0000000000000000 l d .rodata 0000000000000000 .rodata 0000000000000000 l d .note.GNU-stack 0000000000000000 .note.GNU-stack 0000000000000000 l d .eh_frame 0000000000000000 .eh_frame 0000000000000000 l d .comment 0000000000000000 .comment 0000000000000000 g O .bss 0000000000000004 a 0000000000000000 g O .data 0000000000000004 b 0000000000000000 g F .text 0000000000000020 _Z4fun2v 0000000000000000 *UND* 0000000000000000 _GLOBAL_OFFSET_TABLE_ 0000000000000000 *UND* 0000000000000000 printf
l兩個*.o檔案連結的時候:同一作用域出現兩對屬性完全一致的符號自然會出錯,儘管你只定義了一個變數,但是在編譯器眼裡是2個同名變數.