0

I have a project as it:

main.cpp
TaskManager.cpp
Web.cpp (Use HTTPRequest.hpp LIB)

I'm using main.cpp for simple web request, however TaskManager is really big in size, which is why it is in a different file.

TaskManager need to send web request (like main.cpp does) but when I tried to use

#include "Web.cpp"

inside TaskManager.cpp, 60+ errors pops out, obviously I realize this is because Web.cpp is already called inside main.cpp.

But I don't know what to do to be able to use the same functions as Web.cpp from different files.

silverfox
  • 1,568
  • 10
  • 27
xPyth
  • 33
  • 1
  • 4

1 Answers1

3

When importing code from other file into a "main" file, we use something called a header file (.h). Never include a .cpp directly.

For example, you have a file containing some function like this

//test.cpp
int add(int x, int y)
{
    return x + y;
}

So you can create a header file called test.h:

#ifndef TEST_H
#define TEST_H

int add(int x, int y);

#endif

And include it to your main file:

#include <iostream>
#include "test.h" // Insert contents of test.h at this point
 
int main()
{
    std::cout << "The sum of 3 and 4 is " << add(3, 4) << '\n';
    return 0;
}

#ifndef and #define call is called a header guard. It prevents conflict from importing multiple files (which is what you want).

Other advantages of header files: What are the benefits and drawbacks of using header files?

More info:

silverfox
  • 1,568
  • 10
  • 27