-1

How do you call a method from a header file that a .cpp file contains?

For example:

main.cpp

#include <iostream>
#include "test.h"
using namespace std;
int main() {
    sayHelloWorld();
}

test.h

void sayHelloWorld();

test.cpp

#include "test.h"

void sayHelloWorld() {
    printf("HELLO WORLD!\n");
}

Sorry if this seems like an easy question for some of you. :/

Burnie
  • 85
  • 3
  • @George, I just want to test it out. Just for my own practice. – Burnie Oct 27 '16 at 09:57
  • You probably want header guards, but other than that your code is fine (although your question title is misleading) I'm guessing your problem is when you try to link you're getting undefined reference errors? – UKMonkey Oct 27 '16 at 09:57
  • Yes, that's how you do it. What problem are you encountering ? – Quentin Oct 27 '16 at 09:57
  • Also, please [remove that `using namespace std;`](http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice). – Quentin Oct 27 '16 at 09:58
  • Not sure if I am on the same page but you are better off declaring it in the header file and defining it in the cpp file. if you want to call the function from another cpp file just include the header file to that cpp file. – macroland Oct 27 '16 at 10:02

1 Answers1

0

Your example is the standard way of doing this. Remark: in test.cpp you'll need to #include <stdio.h> or better #include <cstdio> in order to use the printf function.

Pat
  • 1,726
  • 11
  • 18