0

I'm trying to use headers in C++. I have calculation.h and calculation.cpp files. I called add and sub function with the necessary arguments which are declared in calculation.h file and implemented in calculation.cpp file. I have included calculation.h file in calculation.cpp file. But whenever I'm trying to run my main.cpp file, It is throwing this error!

[C:\Users\MAHBIN~1\AppData\Local\Temp\ccPy83Oj.o:main.cpp:(.text+0x32): undefined reference to `add(int, int)'

C:\\Users\\MAHBIN\~1\\AppData\\Local\\Temp\\ccPy83Oj.o:main.cpp:(.text+0x65): undefined reference to `sub(int, int)'

collect2.exe: error: ld returned 1 exit status]

(https://i.stack.imgur.com/eU9Gp.png)

main.cpp file:

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

int main(){
    int x=5, y=20;
    cout<<add(x,y)<<endl;
    cout<<sub(x,y)<<endl;
    return 0;
}

calculation.h file:

#pragma once

int add(int, int);
int sub(int, int);

calculation.cpp file:

#include<iostream>
#include"calculation.h"

int add(int x, int y){
    return x+y;
}

int sub(int x, int y){
    if(x<y){
        return y-x;
    }
    else return x-y;
}

But whenever I directly include calculation.cpp file in main.cpp file or calculation.h file, it works! But I want to use the calculation.cpp through including calculation.h.

If I explicitly run this command in terminal, it works! Otherwise, it doesn't!

g++ -o main.exe main.cpp calculation.cpp

cigien
  • 57,834
  • 11
  • 73
  • 112

2 Answers2

1

Running

g++ -o main.exe main.cpp calculation.cpp

is the correct way.

The compiler will not go ahead and compile other .cpp files without you specifying them.

You may be interested in using a tool like CMake if you plan on bigger projects.

Chr L
  • 89
  • 4
0

The first way (the one that doesn't work) just launches this command line:

g++ main.cpp -o main

which compiles main.cpp but not calculation.cpp. Having #include "calculation.h" in main.cpp does not automatically compile calculation.cpp.

The correct way is this:

g++ -o main.exe main.cpp calculation.cpp

It compiles both main.cpp and calculation.cpp and links them together into the executable file main.exe.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115