我目前正在学习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
它将起作用。