Function Implementation in Separate File

此生再无相见时 提交于 2019-12-08 02:56:14

问题


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:


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



回答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.



来源:https://stackoverflow.com/questions/4378219/function-implementation-in-separate-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!