小心使用宏
開發過程中,會經常使用宏定義,偶爾還會碰到重復定義的宏,有些時候會造成不良影響。
見如下例子:
Test.h
#ifndef GUARD_TEST_H #define GUARD_TEST_H class CTest { public: CTest(); virtual ~CTest(); void Display(void); public: int x; #ifdef USE_BIG_ARRAY // 注意這里 #pragma message("CTest use big") char szArray[8]; #else #pragma message("CTest use small") char szArray[4]; #endif int y; }; #endif // end of GUARD_TEST_H
Test.cpp
#include "Test.h" #include <memory.h> #include <stdio.h> CTest::CTest() { x = y = 0; memset(szArray, 0, sizeof(szArray)); } CTest::~CTest() { } void CTest::Display(void) { printf("x = %d, y = %d\n", x, y); printf("array is %s\n", szArray); }
TestEx.h
#ifndef GUARD_TESTEX_H #define GUARD_TESTEX_H #define USE_BIG_ARRAY // 注意這里 class CTestEx { public: CTestEx(); virtual ~CTestEx(); void Display(void); public: int x; #ifdef USE_BIG_ARRAY // 注意這里 #pragma message("CTestEx use big") char szArray[8]; #else #pragma message("CTestEx use small") char szArray[4]; #endif int y; int z; }; #endif // end of GUARD_TESTEX_H
TestEx.cpp
#include "TestEx.h" #include <memory.h> #include <stdio.h> // // Construction/Destruction // CTestEx::CTestEx() { x = y = z = 0; memset(szArray, 0, sizeof(szArray)); } CTestEx::~CTestEx() { } void CTestEx::Display(void) { printf("x = %d, y = %d, z = %d\n", x, y, z); printf("array is %s\n", szArray); }
main.cpp
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "./TestEx.h" // 注意這里 #include "./Test.h" // 注意這里 #define USE_BIG_ARRAY int main() { printf("Hello C++\n"); CTest test; test.Display(); putchar('\n'); test.x = 5; strcpy(test.szArray, "Hello"); test.y = 0; test.Display(); return 0; }
運行結果如下:
顯然,這里的y值不是我們想要的
在編譯的時候,編譯器會有如下提示:
Compiling...
main.cpp
CTestEx use big
CTest use big
Test.cpp
CTest use small
TestEx.cpp
CTestEx use big
Linking..
發現,在兩個不同的編譯單元main.cpp 和 Test.cpp里,szArray的定義是不同的。
這就導致在main里,編譯器認為szArray是8個字節的,在Test里,編譯器認為szArray是4個字節的,這樣在進行操作的時候,
就造成的混亂,就造成了上面的結果
提示:慎用宏定義,尤其是在不同的文件里盡量使用不同的宏定義作為判斷條件
實驗代碼:http://download.csdn.net/source/3044231
轉載于:https://www.cnblogs.com/xkxjy/archive/2011/02/26/2078097.html
總結
- 上一篇: javascript:设置URL参数的方
- 下一篇: iPhone5:4G是否进入主流的风向标