close

轉錄至https://coherence0815.wordpress.com/2014/08/13/multiple-inclusion-problem/

在任何一個編譯單元(translation unit)之中,宣告(Declaration)可以有多次,但是定義(definition)只能有一次,這稱為One Definition Rule(ODR)。

比方說,若你在某個header file中放置了一個function的定義,則有可能會因違反ODR而造成Compiler error,這也是為什麼我們應盡量在header file中只放置宣告,而在.cpp file中才放置定義的原因。

 

違反ODR的例子:
============ In Foo.h ============

1
2
3
4
void Foo()
{
    //This is a function definition
}

============ In Bar.h ============

1
#include "Foo.h"

=========== In Test.cpp ===========

1
2
3
4
5
6
7
#include "Foo.h"
#include "Bar.h"
 
int main()
{
    return 0;
}

以上這段code會在造成以下Compiler error (用Visual Studio 2008 Express測試)

error C2084: function ‘void Foo(void)’ already has a body

解決方法:
在Foo.h中使用#pragma once或#define Guard,以避免multiple inclusion;這兩個方法有各自的優點。

使用#pragma once的優點:
1. 需要打的字比較少
2. 不用去想#define Guard的名字,也不會有#define Guard名字衝突的問題
3. Compile的時間較短

使用#define Guard的優點:
所有的Compiler都支援

Google C++ Style Guide建議使用#define Guard

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 LiLun 的頭像
    LiLun

    LiLun の 分享平台

    LiLun 發表在 痞客邦 留言(0) 人氣()