標頭檔為什麼要加#ifndef #define #endif

來源:互聯網
上載者:User

當你用VC的菜單新增一個類,你會發現自動產生的程式碼總是類似下面的樣子:

#if !defined(AFX_XXXX__INCLUDED_)

#define  AFX_XXXX__INCLUDED_

具體代碼

#endif

       這是為了防止標頭檔被重複包含。重複包含可以用下面的例子來說明:比如有個標頭檔a.h,裡面有個函數Fa;另一個標頭檔b.h,裡面有函數Fb, Fb的實現需要用到Fa,則b.h中需要包含a.h;有個cpp檔案中的函數需要用到Fa和Fb,則需要包含a.h和b.h,此時a.h就發生了重複包含。編譯器,出現如下錯誤:

error C2084: function 'bool __cdecl Fa()' already has a body

解決辦法是在a.h的中加入:

#ifndef A

#define A

原來的代碼

#endif

 

樣本原始碼清單如下:

// a.h

#ifndef A

#define A

 

bool AorB(bool a)

{

       return a;

}

 

#endif

 

// b.h

#include "a.h"

 

bool CorD(bool a)

{

       return AorB(a);

}

 

// a.cpp

#include "a.h"

#include "b.h"

 

int main()

{

       bool a = 0;

       bool b = AorB(a);

       bool c = CorD(b);

 

       getchar();

       return 0;

}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.