开发过程中,会经常使用宏定义,偶尔还会碰到重复定义的宏,有些时候会造成不良影响。
见如下例子:
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
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
#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
//////////////////////////////////////////////////////////////////////
// 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 "./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个字节的,这样在进行操作的时候,
就造成的混乱,就造成了上面的结果
提示:慎用宏定义,尤其是在不同的文件里尽量使用不同的宏定义作为判断条件
原文链接: https://www.cnblogs.com/xkxjy/archive/2011/02/26/2078097.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/21581
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!