說明#ifndef與#pragma once區別

來源:互聯網
上載者:User

今早解決了#ifndef與#pragma once之間區別的疑惑。

為了區別#ifndef與#pragma once的宏定義區別,為此我特意編了點小程式測試了下,過程如下:

1、建立兩個標頭檔Huang1.h和Huang2.h,如下:

   //Huang1.h

#include <iostream.h>

#ifndef HH

#define HH 100

#endif

void Fanh()

{

cout<<HH*2<<endl;

}

   //Huang2.h

#pragma once

#include <iostream.h>

void Fan()

{

cout<<"good"<<endl;

}

2、再建立一個cpp檔案Huang.cpp,如下:

#include <iostream.h>

#include "Huang1.h"

#include "Huang1.h"

#include "Huang2.h"

#include "Huang2.h"

void main()

{

Fan();

Fanh();

}

3、運行,出錯如下:

  --------------------Configuration: eaxm - Win32 Debug--------------------

Compiling...

Huang.cpp

d:/vc實戰演練/eaxm/huang1.h(6) : error C2084: function 'void __cdecl Fanh(void)' already has a body

 從以上可以看出重複調用函數體,因為前面兩次包括標頭檔Huang1.h,於是注釋掉紅色字的標頭檔,

#include <iostream.h>

#include "Huang1.h"

//#include "Huang1.h"

#include "Huang2.h"

#include "Huang2.h"

void main()

{

Fan();

Fanh();

}

再運行,結果為:good

                200

                press  any key to continute

說明結果是對的。

4、但是為什麼兩次"Huang2.h"都不會出問題呢?這恰恰說明了一個問題

   #pragma once則由編譯器提供保證:同一個檔案不會被包含多次。也就是說第一次開啟Huang2.h之後,下一次就不會再開啟Huang2.h了,此時運行到第二次"Huang2.h"時就會跳過,而Huang1.h會重複多次開啟,所以你就會發現調用了多個函數體,也就會出現上面的錯誤。。

     

參考:http://mxdxm.javaeye.com/blog/592542

      http://www.cppblog.com/szhoftuncun/archive/2007/10/28/35356.html

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.