C/C++多重定义实例

main.cpp

#include 
#include 
#include "gh.h"
int main()
{
    printf("%d \n",a);
    return 0;
}

fun.cpp

#include 
#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

1(只编译)没错误,但这该死的水印.

C/C++多重定义实例_第1张图片

链接阶段出现错误,重复定义.

使用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个同名变量.

你可能感兴趣的:(C/C++多重定义实例)