-1

So I have a main.cpp file with a simple hello world program containing a function that prints hello world, and a main method. How do I move only the function that prints hello world into a different .cpp file. I have a main.cpp, function.cpp and function.h files.

I've tried to #include function.h in the function.cpp file but won't work.

// main.cpp
#include <iostream>

std::string funct()
{
    return "hello";
}

int main()
{
    std::cout<<funct()<<std::endl;
    return 0;
}

// function.h
string funct();

//function.cpp
?
James
  • 1
  • 1

1 Answers1

0

It is as simple as

// function.h
#include <string>
std::string funct();

// function.cpp
std::string funct()
{
  return "hello"
}

// main.cpp
#include <iostream>
#include "function.h"

int main()
{
  std::cout << funct() << "\n";
  return 0;
}

In your case you would declare the function in a header file and define it in a cpp file. Don't forget to compile the cpp file and link it in.

Check for example What is the difference between a definition and a declaration?

Tom Trebicky
  • 598
  • 1
  • 4
  • 11
  • Yes I've tried this multiple times but I still get the error code "string" in namespace std does not name a type – James Sep 06 '19 at 15:55
  • Looks like you're still missing includes for `function.h`. And you have addressed the fact that they have another `funct()` in `main.cpp` which will break everything anyways... – scohe001 Sep 06 '19 at 16:04