【发布时间】:2020-10-16 19:03:32
【问题描述】:
所以我有三个文件,main.c、a.h、b.h。
在所有三个文件中,我都声明了以下函数
int test(int a, int b)
{
if(a>b)
return a;
else return b;
}
无论如何我可以在主程序中使用该函数,但从不同的位置(从 a.h,然后从 b.h,然后从 main.c),因为现在我有这个错误:错误:重新定义测试?
为了更好地理解,我将在此处发布声明:
在 a.h 和 b.h 两个库中编写 test()。在一个程序中包含这两个库。调查怎么可能 我使用来自 a.h 或 b.h 的 test()。如果我也在主程序中定义 test() 并且我想使用 来自主程序、库 a.h 或 b.h 的 test() ?
main.c中的代码是这样的:
#include <stdio.h>
#include <stdlib.h>
#include "a.h"
#include "b.h"
int test(int a, int b) //Function for showing the max
{
if(a > b)
return a;
else return b;
}
int main()
{
int a, b;
scanf("%d %d", &a, &b);
test(a, b);
return 0;
}
a.h 中的代码与 b.h 中的代码相同:
#ifndef CODE_a_H
#define CODE_a_H
int test(int a, int b) //Function for showing the max
{
if(a > b)
return a;
else return b;
}
#endif
【问题讨论】:
-
请发帖Minimal, Reproducible Example。似乎您多次定义函数,而不是像
int test(int a, int b);那样声明函数。 -
回答:不要将函数definitions放在头文件中。您可以拥有任意数量的声明(只要它们相同)。
-
通常将声明库中所有函数的头文件与库本身混为一谈。
-
#ifdef USE_A #include "a.h" #else #include "b.h" #endif各占一行。 -
我建议你向你的导师或他们的助教询问练习的意义。当然,@WeatherVane 可能是该练习所预期的方法,但我认为将其描述为“将两个库都包含在一个程序中”是一种延伸。
标签: c function header header-files