內置宏和預編譯指令, 在代碼調試、單元測試、跨平台代碼中經常會用到。這里記錄一下。
1. 內置宏
(文件名,當前行號,當前日期,當前時間,當前執行方法名)
__FILE__
__LINE__
__DATE__
__TIME__
__FUNCTION__
2.預編譯指令
可以防止頭文件被多次引用
可以方便解決代碼跨平台編譯問題
可以根據自定義變量靈活執行程序
等等,許多好處
效果可以看代碼實例:
test.h
1 #ifndef __TEST_H 2 #define __TEST_H 3 4 #include <iostream> 5 6 class Test{ 7 public: 8 Test(int _val){ 9 this->val = _val; 10 } 11 12 void print(){ 13 std::cout << "the val is " << this->val << std::endl; 14 std::cout << "function:" << __FUNCTION__ << std::endl; 15 std::cout << "line:" << __LINE__ << std::endl; 16 } 17 18 #ifdef CODE_TEST //如果定義了CODE_TEST, 則聲明為public; 否則為private 19 public: 20 #else 21 private: 22 #endif 23 int val; 24 }; 25 26 #endif
main.cpp
1 #include "test.h" //test.h使用了預編譯 2 #include "test.h" 3 4 int main(){ 5 Test t(5); 6 t.print(); 7 8 #ifdef CODE_TEST //如果定義了CODE_TEST, 則會執行下面到代碼 9 std::cout << "t.val = " << t.val << std::endl; 10 #endif 11 12 return 0; 13 }
執行: