Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I include other .cpp files

I’ve watched several tutorials on C++ header files and did EXACTLY what they were showing, but I can’t really understand why I can’t use a function from other .cpp file.

Main.cpp

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

int main() {
    std::cout << sum(2, 2);

    return 0;
}

Header.cpp

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#include "Header.h"

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

Header.h

#pragma once

int sum(int a, int b);

>Solution :

Your program is working as can be seen here.

To get your program working on your machine follow these steps(assuming you’re using g++ and Ubuntu:

Step 1: Create a binary/executable using the command:

g++ main.cpp Header.cpp -o myexecutable

Step 2: Test/Run your executable created in the last step using the command:

./myexecutable

Alternate Solution: A shortcut

Now if you’re wondering that you’ve to type the name of every source file to make the executable, then you can take a sigh of relief because there is a shortcut as given below:

Assuming you have many source files(.cpp files) in your current directory and you want to compile them all without writing the names of all of them, then you can use the command:

g++ ./*.cpp -o myexecutable

The above command will create a binary/executable named myexecutable .

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading