【问题标题】:How to use a function which was declared in more than one header如何使用在多个标头中声明的函数
【发布时间】:2020-10-16 19:03:32
【问题描述】:

所以我有三个文件,ma​​in.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


【解决方案1】:

在 dubio pro reo 中。

也许你应该在这个作业中学到一些东西。而“某事”可能是“不要这样做”。

您显然已经了解到,由于重复的符号,这将不起作用。

您可以在预处理器的帮助下生成一个工作程序。

test()的定义扩展为

#ifndef CODE_a_H
#define CODE_a_H

#ifndef TEST_DEFINED
#define TEST_DEFINED
int test(int a, int b) //Function for showing the max
{
    if(a > b)
        return a;
    else return b;
}
#endif
#endif

根据您的主程序中#include 的顺序,您包含的第一个文件的定义将最终出现在程序中。

【讨论】:

    【解决方案2】:

    你不能在两个不同的地方(我的意思是 .c 文件)定义同名的同一个函数并编译所有文件。

    如果您愿意,可以通过条件编译或单独编译文件并根据需要进行链接来控制它。

    primetest.h

    #ifndef __PRIMETEST__
    #define __PRIMETEST__
    
    int primtest(int a, int b);
    
    #endif /* __PRIMETEST__ */
    

    primetest.c

    int primtest(int a, int b) //Function for showing the max
    {
        if(a > b)
            return a;
        else return b;
    }
    

    primetest-2.c

    /* generally we have different code here than previous one*/

    int primtest(int a, int b) //Function for showing the max
    {
        if(a > b)
            return a;
        else return b;
    }
    

    main.c

    #include <stdio.h>
    #include <stdlib.h>
    #include "primetest.h"
    
    int main()
    {
        int a, b;
        scanf("%d %d", &a, &b);
        primtest(a, b);
        return 0;
    }
    

    你可以通过以下方式编译

    gcc main.c primtest.c
    

    gcc main.c primtest-2.c
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多