差異處
這裏顯示兩個版本的差異處。
cpp:mixed:preprocessor [2013/02/24 22:32] 127.0.0.1 外部編輯 |
cpp:mixed:preprocessor [2023/06/25 09:48] |
||
---|---|---|---|
行 1: | 行 1: | ||
- | {{tag>cpp}} | ||
- | ====== Preprocessor使用的小小心得 ====== | ||
- | 在C的程式中,以**#**開頭的在編譯之前都會被優先處理,如用**#include**去包含標頭擋、**#define**巨集處理、**#ifdef**條件編譯。最近接觸到了些open source的c source code,有dll也有driver。這些Preprocessor的宣告,其中用途包含宣告在x86與amd64上type的資料差異外,我認為最好用的是拿來寫debug code。\\ | ||
- | 在VC的BaseTsd.h中用來根據程式執行平台來決定所要使用的指標大小:\\ | ||
- | <code cpp> | ||
- | #if defined(_IA64_) || defined(_AMD64_) | ||
- | #define FIRMWARE_PTR | ||
- | #else | ||
- | #define FIRMWARE_PTR POINTER_32 | ||
- | #endif | ||
- | </code> | ||
- | ===== VC使用與設定範例 ===== | ||
- | 下面是在VC2008的範例:\\ | ||
- | 首先宣告了一個DebugUtil類別,提供log方法。(這僅是個範例,如果要全面一些還可以提供如level的功能) | ||
- | <code cpp> | ||
- | #include <string> | ||
- | #include <iostream> | ||
- | using namespace std; | ||
- | |||
- | class DebugUtil { | ||
- | public: | ||
- | static void log(string aMessage); | ||
- | }; | ||
- | </code> | ||
- | 接著是使用到preprocessor的部分:\\ | ||
- | 這裡使用了#if去確認_DEBUG有被宣告就會將訊息給印出來。 | ||
- | <code cpp> | ||
- | #include "stdafx.h" | ||
- | #include "debug.h" | ||
- | |||
- | void DebugUtil::log(string aMessage){ | ||
- | #if _DEBUG | ||
- | cout << aMessage << endl; | ||
- | #endif | ||
- | } | ||
- | </code> | ||
- | 最後是組態設定,點選建置>組態管理員,到C/C++的前置處理器選單可以看到已定義項目:\\ | ||
- | 在VC中預設已經幫你設定好Release與Debug不同的建置組態,在Debug中它會把_DEBUG給加入定義項目。因此我們僅需要將log code給放入程式碼中即可。\\ | ||
- | {{:cpp:mixed:preprocessor_defined.png|}}\\ | ||
- | ===== Eclipse使用與設定範例 ===== | ||
- | 在Eclipe中,也可以透過設定Preprocessor的項目。\\ | ||
- | {{:cpp:mixed:preprocessor_defined_eclipse.png|}}\\ | ||
- | |||
- | 不管是VC或是Eclipse,所設置的preprocessor都會被以參數D加入compiler參數中。在Debug上,VC和Eclipse都有提供其他管道讓使用者方便debug,這部分就原諒小弟才疏學淺了。\\ | ||
- | |||
- | 發自內心的獨白: 在念書的時後完全不知道這些,當看的程式越來越多,知道的也越來越多。 |