Undefined reference to function in C program

核能气质少年 提交于 2021-02-08 12:01:20

问题


I'm kind of new in C programming. To be honest this is my first program where I am using Function. But it's not working. Can anyone tell me what is supposed to be the problem?

// 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;
}

}

回答1:


you did not call your function.

Write your method (freezingCalculation etc) outside of main function and do not forget to return as your main function return type is integer.Like--

#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;
}



回答2:


The problem is, you are trying to define functions inside the main() function. This is not allowed in pure C. Some compiler extensions allows "nested functions", but that's not part of the standard.

What happens here is, the compiler sees the function declarations but cannot find any definition to the functions as they are not in file scope.

You need to move the function definitions out of main() and call the functions from main() as per the requirement.



来源:https://stackoverflow.com/questions/41519273/undefined-reference-to-function-in-c-program

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!