0

I would like if possible know how I can resolve this issue:

I have 3 files, all 3 are in the same folder: function.h, function.cpp and main.cpp The compiler is gcc. the error message is:

undefined reference to `add(int, int)'
collect2.exe: error: ld returned 1 exit status

function.h

int add(int a, int b);

function.cpp

int add(int a, int b)
{
    return a + b;
}

main.cpp

#include<iostream>
#include "functions.h"
using namespace std;

int main()
{
    int n1 = 0; int n2 = 0; int sum = 0;
    cout << "Please insert two numbers:" << endl;
    cin >> n1; cin >> n2 ;    
    sum = add(n1, n2) ; 
    cout << "The sum is:" << sum << endl ;
}

Command line

g++ main.cpp

if I include function.cpp to header of main.cpp the error message disapears
Should I add some extra config to let gcc linker know where to look for functions definitions?

thanks

Anouar
  • 51
  • 8
  • 1
    TL;DR of the dupe: You need to compile all of the cpp files that have the code you need together. `g++ main.cpp` -> `g++ main.cpp function.cpp` – NathanOliver Jan 12 '23 at 14:05

0 Answers0