C++ 重复引用符号 问题 Inline keyword

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// h.hpp
#ifndef _H_HPP
#define _H_HPP

void h()
{
...
}

#endif

-----------------------------------------------------

// a.cpp

#include "h.hpp"

int main()
{
h();
return 0;
}

-----------------------------------------------------

// b.cpp

#include "h.hpp"

void b()
{
h();
}

执行下面的编译语句:

1
g++ a.cpp b.cpp -o main

通过inline 或者 static 来解决在编译过程中产生相同符合的问题。

使用static,最终会产生两个不同的函数符号

使用inline 被 include 进多个编译单元的 h 函数,在多个编译单元中分别编译,得到了多个副本;在链接的时候,链接器随便选取其中的一个副本保留,其余的被丢弃。