#pragma directive

一:#pragma warning指令

該指令允許有選擇性的修改編譯器的警告消息的行爲
指令格式如下:
#pragma warning( warning-specifier : warning-number-list [; warning-specifier : warning-number-list...]
#pragma warning( push[ ,n ] )
#pragma warning( pop )

主要用到的警告表示有如下幾個:

once:只顯示一次(警告/錯誤等)消息
default:重置編譯器的警告行爲到默認狀態
1,2,3,4:四個警告級別
disable:禁止指定的警告信息
error:將指定的警告信息作爲錯誤報告

如果大家對上面的解釋不是很理解,可以參考一下下面的例子及說明

#pragma warning( disable : 4507 34; once : 4385; error : 164 )
等價於:
#pragma warning(disable:4507 34) // 不顯示4507和34號警告信息
#pragma warning(once:4385)        // 4385號警告信息僅報告一次
#pragma warning(error:164)        // 把164號警告信息作爲一個錯誤。
同時這個pragma warning 也支持如下格式:
#pragma warning( push [ ,n ] )
#pragma warning( pop )
這裏n代表一個警告等級(1---4)。
#pragma warning( push )保存所有警告信息的現有的警告狀態。
#pragma warning( push, n)保存所有警告信息的現有的警告狀態,並且把全局警告
等級設定爲n。 
#pragma warning( pop )向棧中彈出最後一個警告信息,在入棧和出棧之間所作的
一切改動取消。例如:
#pragma warning( push )
#pragma warning( disable : 4705 )
#pragma warning( disable : 4706 )
#pragma warning( disable : 4707 )
#pragma warning( pop )

在這段代碼的最後,重新保存所有的警告信息(包括4705,4706和4707)

在使用標準C++進行編程的時候經常會得到很多的警告信息,而這些警告信息都是不必要的提示,
所以我們可以使用#pragma warning(disable:4786)來禁止該類型的警告

在vc中使用ADO的時候也會得到不必要的警告信息,這個時候我們可以通過
#pragma warning(disable:4146)來消除該類型的警告信息

二:#pragma pack()
注:如果設置的值比結構體中字節最長的類型還要大,則這個變量(注意僅針對這一個變量)只按照它的字節長度對齊,即不會出現內存浪費的情況。請參見(4)。
(1)
#pragma pack(1)        //每個變量按照1字節對齊
struct A
{
char x;    //aligned on byte boundary 0
int y;     //aligned on byte boundary 1
}a;
sizeof(a)==5
(2)
#pragma pack(2)        //每個變量按照2字節對齊
struct A
{
char x;    //aligned on byte boundary 0
int y;     //aligned on byte boundary 2
}a;
sizeof(a)==6
(3)
#pragma pack(4)        //每個變量按照4字節對齊
struct A
{
char x;    //aligned on byte boundary 0
int y;     //aligned on byte boundary 4
}a;
sizeof(a)==8
(4)
#pragma pack()        //默認,相當於#pragma pack(8) 每個變量按照8字節對齊
struct A
{
char x;    //aligned on byte boundary 0
int y;     //aligned on byte boundary 4
}a;
sizeof(a)==8
但是這裏y的大小是4字節,所以不會按照8字節對齊,否則將造成1個int空間的浪費

三.#pragma comment
The following pragma causes the linker to search for the EMAPI.LIB library while linking. The linker searches first in the current working directory and then in the path specified in the LIB environment variable:
#pragma comment( lib, "emapi" )


四.#pragma deprecated
When the compiler encounters a deprecated symbol, it issues C4995:
void func1(void) {}
void func2(void) {}
int main() {
   func1();
   func2();
   #pragma deprecated(func1, func2)
   func1();   // C4995
   func2();   // C4995
}


五.#pragma message
The following code fragment uses the message pragma to display a message during compilation:
#if _M_IX86 == 500
#pragma message( "Pentium processor build" )
#endif
發佈了36 篇原創文章 · 獲贊 2 · 訪問量 19萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章