C语言:标头包含导致意外行为

C语言:标头包含导致意外行为,c,header-files,C,Header Files,我现在有一个严重的问题,我真的想找出根本原因 函数源文件: //function.c #include "function.h" void FunctionA (int tiFrame) { printf ("%d", tiFrame); } 函数头文件: //function.h extern void FunctionA (int tiFrame); // stupid.h #define tiFrame TIFRAME 愚蠢的外部头文件: //function.h exte

我现在有一个严重的问题,我真的想找出根本原因

函数源文件:

//function.c
#include "function.h"
void FunctionA (int tiFrame)
{
     printf ("%d", tiFrame);
}
函数头文件:

//function.h
extern void FunctionA (int tiFrame);
// stupid.h
#define tiFrame TIFRAME
愚蠢的外部头文件:

//function.h
extern void FunctionA (int tiFrame);
// stupid.h
#define tiFrame TIFRAME
应用程序:

//application.c
#include "stupid.h"
#include "function.h"

void App2 ()
{
    FunctionA (10);
}
结果:Function始终打印“0”(零值)

现在,我更改了应用程序文件:

//application.c
#include "function.h"
#include "stupid.h"

void App2 ()
{
    FunctionA (10);
}
结果:FunctionA总是打印“10”(正确!)


有人知道根本原因吗?

从“dumby.h”标题泄漏的#define与函数定义发生冲突

您可以插入printf来查找TIFRAME的值

printf("%d\n", TIFRAME);
或者,更巧妙地,使用符号粘贴将TIFRAME转换为字符串

或者,只是修复/避免。您在此处添加的“dumby.h”扩展了#tiFrame的定义

#define tiFrame TIFRAME
所以要避免这个碰撞,

//function.c
#include "function.h"
void FunctionA (int arg_tiFrame)
{
     printf ("%d", arg_tiFrame);
}
你甚至不需要在这里提及arg名称

//function.h
extern void FunctionA (int);
或者,您可以在函数之前取消定义tiFrame

//stupid.h declares tiFrame, gotta avoid that
#define CleverAvoidance tiFrame
#undef tiFrame
//function.c
#include "function.h"
void FunctionA (int tiFrame)
{
     printf ("%d", tiFrame);
}
//and put it back the way it was, or just fugeddaboudit
#define tiFrame CleverAvoidance

不同的行为是由
预处理
程序引起的

案例1

#include "stupid.h"
#include "function.h"
#include "function.h"
#include "stupid.h"
预处理之后

#define tiFrame TIFRAME
extern void FunctionA (int TIRAME); //the parameter is changed to const
void App2 ()
{
    FunctionA (10); //the call parameter is still the const TIRAME
}
extern void FunctionA (int tiFrame); //the parameter is still the varibale
#define tiFrame TIFRAME
void App2 ()
{
    FunctionA (10); //the parameter is 10 in this case
}
案例2

#include "stupid.h"
#include "function.h"
#include "function.h"
#include "stupid.h"
预处理之后

#define tiFrame TIFRAME
extern void FunctionA (int TIRAME); //the parameter is changed to const
void App2 ()
{
    FunctionA (10); //the call parameter is still the const TIRAME
}
extern void FunctionA (int tiFrame); //the parameter is still the varibale
#define tiFrame TIFRAME
void App2 ()
{
    FunctionA (10); //the parameter is 10 in this case
}

PS:您最好不要编写这样令人困惑的代码。遵循
KISS
原则,因为其他人可能会阅读和使用您的代码。

请参阅application.c的预处理输出。它可能会给出一些提示。@KhangLe什么是TIFRAME?@mangusta:#定义TIFRAME 15。顺便说一句,“tiFrame”的定义必须删除,但它没有删除,所以我坚持使用它预处理器会将
tiFrame
更改为
tiFrame
,可能为0。很可能头文件中的内容比您显示的要多。您好!这是我项目中的一个真实情况。由于机密性,我不得不更改函数名和文件名。您开发组件的时间太长了,现在您发现一些新的宏与您的宏同名。如果您对
宏使用
UPCASE
,对
参数使用
downcase
。你不会有这个问题。