typedef:
如果放在所有函數之外,它的作用域就是從它定義開始直到文件尾;
如果放在某個函數內,定義域就是從定義開始直到該函數結尾;
#define:
不管是在某個函數內,還是在所有函數之外,作用域都是從定義開始直到整個文件結尾。
define在同一編譯單元內部,就算在不同的命名空間內,其作用范圍不變。也就是從定義處一直到文件介紹。
看下面這個例子:
Main.cpp
/** * @file Main.cpp * @author chenjiashou(chenjiashou@baidu.com) * @date 2017/09/19 17:37:33 * @version $Revision$ * @brief * **/ #include <iostream> #include "test1.h" #define LL 2 typedef long long ll; void test_typedef() { typedef int x_int; x_int a = 1; } namespace other { #define OTHER //不在乎是否在命名空間中 //關鍵在一個編譯單元 } int main() { #ifdef LL std::cout << "LL define" << std::endl; #endif #ifdef SS std::cout << "SS define" << std::endl; #endif #ifdef OTHER std::cout << "OTHER define" << std::endl; #endif ll a = 1; print(); //x_int b = 1;//compile error return 0; } /* vim: set ts=4 sw=4 sts=4 tw=100 */
test1.h
/** * @file test1.h * @author chenjiashou(chenjiashou@baidu.com) * @date 2017/09/19 17:39:05 * @version $Revision$ * @brief * **/ #ifndef TEST1_H #define TEST1_H #endif // TEST1_H void print(); /* vim: set ts=4 sw=4 sts=4 tw=100 */
test1.cpp
/** * @file test1.cpp * @author chenjiashou(chenjiashou@baidu.com) * @date 2017/09/19 17:36:15 * @version $Revision$ * @brief * **/ #include <iostream> #define SS 1 void print() { #ifdef SS std::cout << "SS define" << std::endl; #endif #ifdef LL std::cout << "LL define" << std::endl; #endif // ll c = 1; //compile error // std::cout << c << endl; } /* vim: set ts=4 sw=4 sts=4 tw=100 */
最后結果:
LL define
OTHER define
SS define