【问题标题】:How to properly create a C function (including header file)如何正确创建 C 函数(包括头文件)
【发布时间】:2016-03-09 06:26:28
【问题描述】:

我正在尝试在 C 中创建自己的函数,然后将 #include 与头文件一起使用。我知道如何制作头文件,并且我已经编写了 .c 函数。但是,当我尝试编译 .c 时,我收到一条错误消息,提示“[Linker error] undefined reference to 'WinMain@16'”并且无法编译。 然后,如果我尝试在程序中使用它,它会显示“[Warning] no newline at end of file”,然后是“[Linker error] undefined reference to validf(int, int, int)”。 有人可以帮忙吗?

功能代码:

int validf(int current,int max, int zero)
{
    if(zero==1)
    {
        if(current>max || current<0)
        {
            printf("Invalid Input");
            return 0; 
        }
        else
        {
            return 1;
        }
    }
    else if(zero==0)
    {
        if(current>max || current<=0)
        {
            printf("Invalid Input");
            return 0;
        }
        else
        {
            return 1;
        }
    }
    else
    {
        printf("Invalid parameters");
        return -1;
    }
}

主代码:

#include<stdio.h>
#include<stdlib.h>
#include "validf.h"

int main()
{
  int valid=0;
  valid=validf(4,5,0);
  printf("%d",valid);
  system("\npause");
  return 0;
}

标题代码:

#ifndef VALIDF_H_  
#define VALIDF_H_  
int validf(int current,int max,int zero);  
#endif

【问题讨论】:

  • main 函数是你写的吗?
  • 您使用的是什么 IDE?如果您使用的是 Eclipse,您可能必须先保存文件并编译。
  • 代码是header应该添加的函数,不是使用函数的代码。我正在使用 Dev C++(我不是我的错,我们别无选择)。
  • 把主代码也贴出来会更好。
  • 您的代码很好并且运行正常..这似乎是一个 dev c++ 问题。也许它没有找到文件

标签: c dev-c++


【解决方案1】:

您的程序由 3 个文件组成:

validfvalidf.h 头文件。包含validf 函数的声明

validf.cvalidf 的代码文件。包含validf 函数的定义。

main.c 包含main 函数。您可能为此文件选择了另一个名称。

在您的 IDE 中,您应该创建一个包含这些文件的项目。 您还需要配置生成的程序的名称。我不熟悉那个特定的 IDE,但它通常在 Project-&gt;Settings-&gt;Compile or Build or Link 下完成。

这将使您的 IDE 编译两个 .c 文件,然后将它们链接到一个程序中。

如果您不创建项目,IDE 可能会将每个.c 文件视为不同的程序,这将导致您提到的错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-16
    • 2012-02-12
    • 2010-11-15
    • 2020-03-11
    • 1970-01-01
    • 2021-12-01
    • 2019-09-26
    • 2012-02-11
    相关资源
    最近更新 更多