【问题标题】:Undefined reference to function in C programC程序中对函数的未定义引用
【发布时间】:2017-01-07 08:06:25
【问题描述】:

我是 C 编程的新手。老实说,这是我第一个使用 Function 的程序。但它不起作用。谁能告诉我应该是什么问题?

// Convert freezing and boiling point of water into Fahrenheit and Kelvin

#include<stdio.h>

void calculation(int);
void freezingCalculation(void);
void boilingCalculation(void);

int main (){

int temperature, fahrenheit, kelvin;


void freezingCalculation(void){
   int temperature = 0;
    calculation(temperature);
 printf("Freezing point in Fahrenheit is %d. \n", fahrenheit);
   printf("Freezing point in Kelvin is %d. \n", kelvin);
}

void boilingCalculation(void){
    int temperature = 100;
    calculation(temperature);
    printf("Boiling point in Fahrenheit is %d. \n", fahrenheit);
    printf("Boiling point in Kelvin is %d. \n", kelvin);
}

void calculation(int temperature){
    //Temperature in fahrenheit
    fahrenheit = ((temperature * 9) / 5) + 32;

    //Temperature in Kelvin
    kelvin = temperature + 273;
}

}

【问题讨论】:

  • 你能用错误信息的实际细节、行号或未定义的函数来更新你的答案吗?
  • 您可能希望在编写更多代码之前获得a good book on C - 研究它会为您节省大量时间和烦恼。
  • 感谢您的建议。 @保罗R
  • 代码中现在没有错误消息。它只是不打印报表。 @miltonb

标签: c nested-function


【解决方案1】:

问题是,您试图在main() 函数 定义函数。这在纯 C 中是不允许的。Some compiler extensions allows "nested functions", but that's not part of the standard

这里发生的情况是,编译器看到函数声明但找不到函数的任何定义,因为它们不在文件范围中。

您需要将函数定义移出main(),并根据要求从main()调用函数。

【讨论】:

  • 谢谢。问题已经解决了。虽然它没有打印出我的预期。看来我的代码还是有一些错误。
  • @RubelHosen 那是因为,您正在执行整数除法。见this answer
【解决方案2】:

你没有调用你的函数。

在主函数之外编写你的方法(freezingCalculation 等),不要忘记返回,因为你的主函数返回类型是整数。喜欢--

#include <stdio.h>
int temperature, fahrenheit, kelvin;
void calculation(int);
void freezingCalculation(void);
void boilingCalculation(void);

int main (){



    freezingCalculation();
    boilingCalculation();

    return 0;
}
void freezingCalculation(void){
   int temperature = 0;
    calculation(temperature);
 printf("Freezing point in Fahrenheit is %d. \n", fahrenheit);
   printf("Freezing point in Kelvin is %d. \n", kelvin);
}

void boilingCalculation(void){
    int temperature = 100;
    calculation(temperature);
    printf("Boiling point in Fahrenheit is %d. \n", fahrenheit);
    printf("Boiling point in Kelvin is %d. \n", kelvin);
}

void calculation(int temperature){
    //Temperature in fahrenheit
    fahrenheit = ((temperature * 9) / 5) + 32;

    //Temperature in Kelvin
    kelvin = temperature + 273;
}

【讨论】:

  • 谢谢。它有很大帮助。但我仍然没有得到我的结果。你能告诉我为什么吗?
  • 你想看到什么结果?它不是打印了所有 4 条语句吗?
  • 是的,我愿意。但是什么都没有打印。 :(
  • 这里打印所有 4 个语句。您在哪里运行此代码?你试过我的代码了吗?
  • 我的错误。现在正在打印。我错过了键入两行。非常感谢兄弟。学到了很多:D
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-05-07
  • 2016-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多