小心使用宏

    技术2022-05-20  55

    开发过程中,会经常使用宏定义,偶尔还会碰到重复定义的宏,有些时候会造成不良影响。

    见如下例子:

    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.cppCTestEx use bigCTest use bigTest.cppCTest use smallTestEx.cppCTestEx use bigLinking..


    发现,在两个不同的编译单元main.cpp 和 Test.cpp里,szArray的定义是不同的。

    这就导致在main里,编译器认为szArray是8个字节的,在Test里,编译器认为szArray是4个字节的,这样在进行操作的时候,

    就造成的混乱,就造成了上面的结果

     

    提示:慎用宏定义,尤其是在不同的文件里尽量使用不同的宏定义作为判断条件

     

    实验代码:http://download.csdn.net/source/3044231

     

     

     

     


    最新回复(0)