一个隐蔽的C语言问题反思

  今天在编译一个C代码的时候,从别的编译ok的头文件中拷贝了一份在上面做修改,没想到修改好之后一直

无法调用这个头文件中的函数和变量。看了好久,才在预编译宏中找到了问题的根源。代码

如下所示:

头文件A:

#ifndef __I2S_LOOP_TEST_H__
#define __I2S_LOOP_TEST_H__

#ifdef __cplusplus
extern "C" {
#endif
int testa = 16;
#ifdef __cplusplus
}
#endif    
         
#endif 

插入头文件B:

#ifndef __I2S_LOOP_TEST_H__
#define __I2S_LOOP_TEST_H__

#ifdef __cplusplus
extern "C" {
#endif
int testb = 20;
#ifdef __cplusplus
}
#endif

#endif

插入测试函数:

#include <stdio.h>
#include "checka.h"
#include "checkb.h"

int main()
{

        testa = 1;
        testb = 3;
        printf("testa:%d testb:%d",testa,testb);

        return 0;
}

运行结果:

test.c: In function ‘main’:
test.c:8:2: error: ‘testa’ undeclared (first use in this function)
  testa = 1;
  ^
test.c:8:2: note: each undeclared identifier is reported only once for each function it appears in

问题原因,是两个头文件中的预编译宏是一样的,会导致另外一个不会被运行。修改要给预编译宏即可。

原文地址:https://www.cnblogs.com/dylancao/p/8000655.html