Simple C++ Error: “… undeclared (first use this function)”

后端 未结 3 1963
醉话见心
醉话见心 2020-12-21 05:52

I am working on my first C++ program for school. For some reason I am getting the following error when I try to compile it:

`truncate\' undeclared (first use          


        
相关标签:
3条回答
  • 2020-12-21 06:29

    You need forward declaration before your main:

    double truncate(double d);
    double round(double d);
    

    You could just define your functions before main, that will solve the problem too:

    #include <iostream>
    #include <math.h>
    
    using namespace std;
    
    #define CENTIMETERS_IN_INCH 2.54
    #define POUNDS_IN_KILOGRAM 2.2
    
    // round result
    double round(double d) {
       return floor(d + 0.5);
    }
    
    // round and truncate to 1 decimal place
    double truncate(double d) {
       return round(double * 10) / 10;
    }
    
    int main() {
    ...
    }
    
    0 讨论(0)
  • 2020-12-21 06:49

    You need to declare functions before you use them. Moving the definitions of truncate and round above the main function should do the trick.

    0 讨论(0)
  • 2020-12-21 06:54

    You are attempting to call a function truncate() at:

    centimeters = truncate(centimeters);
    

    You have not yet told the compiler what that function is, so it is undefined and the compiler is objecting.

    In C++, all functions must be declared (or defined) before they are used. If you think you are using a standard C++ library function, you need to include its header. If you are not sure that you are using a C++ library function, you need to declare and define your own.

    Be aware that on POSIX-based systems, truncate() is a system call that truncates an existing file; it will have a different prototype from what you are trying to use.


    Further down your code - hidden off the bottom of the scroll bar - are the function definitions for truncate() and round(). Put the function definitions at the top of the file, so that the compiler knows about their signature before they are used. Or add forward declarations of the functions at the top of the file and leave the definitions where they are.

    0 讨论(0)
提交回复
热议问题