Function implementation in a separate file

What is the correct syntax for implementing a function in a separate file? For instance:

foo.h

int Multiply(const int Number);

foo.cpp

#include "foo.h"

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

I see that this is a lot, but when I try, I get an error related to a missing function main(). I get an error even when I try to compile working code.

+3
source share
2 answers

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

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

#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;
}

, ( main() foo.cpp, ):

main.cpp

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

using namespace std;

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

g++ main.cpp foo.cpp
+7

++ , .

, int main(). , .

, . .

+2

Source: https://habr.com/ru/post/1778982/


All Articles