Home > Article > Backend Development > How to solve C++ compilation error: 'undefined reference to 'function'?
Solution to C compilation error: 'undefined reference to 'function', how to solve it?
1. Problem description
In the process of using C programming, we often encounter compilation errors. One of the common errors is "undefined reference to 'function'". This error message indicates that a certain The reference to the function is undefined. This error usually occurs during the linking phase, when the compiler cannot find the definition of the function, causing compilation to fail.
2. Cause of the error
3. Solution
In view of the above error reasons, several common solutions are provided below.
// function.h int sum(int a, int b);
// main.cpp #include "function.h" int main() { int result = sum(1, 2); return 0; }
In the above code, we only provide the function declaration, but not the function definition. In order to solve this problem, we need to provide the definition of the function in the appropriate location:
// function.cpp int sum(int a, int b) { return a + b; }
In this way, at compile time, the compiler can find the actual definition of the function, thereby solving the problem of "undefined reference to 'function'" mistake.
Consider the following code example:
// function.h float sum(int a, int b); // 函数声明
// function.cpp int sum(int a, int b) { // 函数定义 return a + b; }
In the above code, the function declaration and the defined return value type are inconsistent, one is declared as float type, and the other is defined as int type. This will cause the compiler to be unable to correctly match the reference and definition of the function, resulting in an "undefined reference to 'function'" error.
In order to solve this problem, we only need to keep the declaration of the function consistent with the defined return value type:
// function.h int sum(int a, int b); // 函数声明
// function.cpp int sum(int a, int b) { // 函数定义 return a + b; }
In this way, the compiler can correctly match the reference and definition of the function, Fixed "undefined reference to 'function'" error.
4. Summary
In C programming, compilation errors are no stranger to us. One of the common errors is "undefined reference to 'function'", which means that a reference to a function has no definition found. To solve this problem, we need to pay attention to whether the definition of the function is provided, and whether the declaration of the function is consistent with its definition. This problem can be easily solved by correctly providing the definition of the function and keeping the function declaration consistent with the definition.
The above is the detailed content of How to solve C++ compilation error: 'undefined reference to 'function'?. For more information, please follow other related articles on the PHP Chinese website!