Error while compiling cpp code: collect2: error: ld returned 1 exit status
Error while compiling cpp code: collect2: error: ld returned 1 exit status
我目前正在学习 C++,并且在学习如何处理多个文件时遇到了这个编译器错误:
" 在函数 main':
bravo.cpp:(.text+0x71): undefined reference to
sum(int, int)'
collect2:错误:ld 返回了 1 个退出状态“
我正在构建的代码是:
主要功能
#include<iostream>
#include "add.h"
int main(){
int a,b;
std::cout<<"Give me two numbers to add: \n";
//std::cin>>a>>b;
std::cout<<"The sum of two numbers is "<< sum(10,5)<< std::endl;
}
头文件
#pragma once
int sum(int a, int b);
求和函数
#include<iostream>
#include "add.h"
int sum(int a, int b){
return a+b;
}
那么我哪里出错了?
我尝试检查堆栈溢出错误,但无法针对我的问题实施解决方案?
有任何想法吗?
谢谢。
您收到链接器错误,因为您可能刚刚尝试编译 main.cpp 函数。然后链接器找不到 sum(int, int),因为您也没有编译 add.cpp 函数。
假设您使用的是 g++,您可以像这样编译这两个文件:
g++ main.cpp add.cpp
它会起作用的。
我目前正在学习 C++,并且在学习如何处理多个文件时遇到了这个编译器错误:
" 在函数 main':
bravo.cpp:(.text+0x71): undefined reference to
sum(int, int)'
collect2:错误:ld 返回了 1 个退出状态“
我正在构建的代码是: 主要功能
#include<iostream>
#include "add.h"
int main(){
int a,b;
std::cout<<"Give me two numbers to add: \n";
//std::cin>>a>>b;
std::cout<<"The sum of two numbers is "<< sum(10,5)<< std::endl;
}
头文件
#pragma once
int sum(int a, int b);
求和函数
#include<iostream>
#include "add.h"
int sum(int a, int b){
return a+b;
}
那么我哪里出错了? 我尝试检查堆栈溢出错误,但无法针对我的问题实施解决方案? 有任何想法吗? 谢谢。
您收到链接器错误,因为您可能刚刚尝试编译 main.cpp 函数。然后链接器找不到 sum(int, int),因为您也没有编译 add.cpp 函数。
假设您使用的是 g++,您可以像这样编译这两个文件:
g++ main.cpp add.cpp
它会起作用的。