内置宏和预编译指令, 在代码调试、单元测试、跨平台代码中经常会用到。这里记录一下。
1. 内置宏
(文件名,当前行号,当前日期,当前时间,当前执行方法名)
__FILE__
__LINE__
__DATE__
__TIME__
__FUNCTION__
2.预编译指令
可以防止头文件被多次引用
可以方便解决代码跨平台编译问题
可以根据自定义变量灵活执行程序
等等,许多好处
效果可以看代码实例:
test.h
#ifndef __TEST_H
#define __TEST_H #include <iostream> class Test{
public:
Test(int _val){
this->val = _val;
} void print(){
std::cout << "the val is " << this->val << std::endl;
std::cout << "function:" << __FUNCTION__ << std::endl;
std::cout << "line:" << __LINE__ << std::endl;
} #ifdef CODE_TEST //如果定义了CODE_TEST, 则声明为public; 否则为private
public:
#else
private:
#endif
int val;
}; #endif
main.cpp
#include "test.h" //test.h使用了预编译
#include "test.h" int main(){
Test t();
t.print(); #ifdef CODE_TEST //如果定义了CODE_TEST, 则会执行下面到代码
std::cout << "t.val = " << t.val << std::endl;
#endif return ;
}
执行: