尽管使用了#include,但隐式声明了函数

时间:2020-06-30 16:49:40

标签: c

我知道这个问题已经被问了很多遍了,但是没有一个解决方案起作用。这是我拥有的简单测试代码。

test.h

#ifdef TEST_H
#define TEST_H

int return_int_3();

#endif

test.c

#include "test.h"

int return_int_3() {
  return 3;
}

main.c

#include "test.h"
#include <stdio.h>

int main(void) {
  printf("%d", return_int_3());
  return 0;
}

我看不出有什么问题。一种解决方案是,必须将包含“ test.h”的内容放在最上面。其他解决方案则说您必须在使用main之前声明该函数,我认为#include可以解决这个问题。因此,我对问题所在感到困惑。它确实可以工作并产生正确的输出,但是解决此问题的正确方法是什么?如果有帮助,我正在使用gcc版本10.1.0。谢谢。

1 个答案:

答案 0 :(得分:3)

正如乔纳森所说,您的问题在test.h文件中

#ifdef TEST_H
#define TEST_H

int return_int_3();

#endif

由于未定义TEST_H,因此未使用ifdef和endif之间的代码。 您需要使用ifndef

#ifndef TEST_H
#define TEST_H

int return_int_3();

#endif

这里TEST_H没有定义,因此使用了代码,设置了TEST_H,因此double include没问题。