简体   繁体   中英

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM