Maxpm
Maxpm

Reputation: 25602

Function Implementation in Separate File

What is the correct syntax for having function implementation in a separate file? For example:

foo.h

int Multiply(const int Number);

foo.cpp

#include "foo.h"

int Multiply(const int Number)
{
    return Number * 2;
}

I see this used a lot, but when I try it I get an error having to do with a missing main() function. I get the error even when I try to compile working code.

Upvotes: 2

Views: 12446

Answers (2)

Armen Tsirunyan
Armen Tsirunyan

Reputation: 133092

Every program in C++ is a collection of one or more translation units, aka source files.

After these files get compiled, the linker searches for the entry point of your program aka the int main() function. Since it fails to find it it gives you an error.

Don't forget that building the program is yielding an executable file. An executable file without an entry point is nonsense.

Upvotes: 2

Andreas Wong
Andreas Wong

Reputation: 60584

Roughly speaking, you need to have a main() function inside one of your C++ files you are compiling.

As the compiler says, you just need to have a main() method inside your foo.cpp, like so:

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

using namespace std;

int Multiply(const int Number)
{
    return Number * 2;
}

int main() {
    // your "main" program implementation goes here
    cout << Multiply(3) << endl;
    return 0;
}

Or you could separate your main function into a different file, like so (omit the main() block in foo.cpp if you intend to do this):

main.cpp

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

using namespace std;

int main() {
   cout << Multiply(3) << endl;
   return 0;
}

Then compile it like

g++ main.cpp foo.cpp

Upvotes: 6

Related Questions