2

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.

1
  • 1
    You should have mentioned that this is supposed to be a library without a main. Just change the configuration type of your project, if you're using Visual Studio, to a library. Commented Dec 7, 2010 at 16:21

2 Answers 2

6

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
Sign up to request clarification or add additional context in comments.

3 Comments

Does the main function need to return anything? Also, I don't see main anywhere in my apstring.cpp file (which compliments apstring.h).
Usually what people do is separate main function and the "helper" functions. See my edit
@SiGanteng : Why is it that in main.cpp "foo.h" is included and not "foo.cpp".Because foo.cpp is what has the function definition and it also includes foo.h.So why not include "foo.cpp" in main.cpp
2

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.

2 Comments

This is for a framework, though; it's not supposed to have a standalone executable.
Then it should be built as a .lib or .dll (in windows). Although a dll can also have an entry point

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.