문제

I was wondering if its possible to define main() inside a class, something like:

struct runtime_entry_point
{
    friend int main()
    {

    }
};

I have tested that and it doesn't work (Almost in GCC 4.8.2):

g++ -o dist/Release/GNU-Linux-x86/turbo build/Release/GNU-Linux-x86/main.o /usr/lib/gcc/x86_64-unknown-linux-gnu/4.8.2/../../../../lib/crt1.o: In function `_start': collect2: error: ld exited with status 1

This sounds to me like a no definition of main() error.

Later, I have written main in the classic way:

struct runtime_entry_point
{
    friend int main()
    {

    }
};

int main(){}

Now the compilation fails because int main() was already defined inside the struct runtime_entry_point! Whats happening here?

도움이 되었습니까?

해결책 2

Аccording to the article on cppreference.com, the following construction:

struct runtime_entry_point
{
    friend int main()
    {
    }
};

Defines a non-member function, and makes it a friend of this class at the same time. Such non-member function is always inline.

Linker couldn't find main() in object file (inline function), and you can't declare another main() in the same translation unit (as it already declared).

다른 팁

Trivially it is not possible to write main as a part of a class/struct. The linker by default searches for a free main method and links against it, makes it the entry point. You may alter this behavior by at the linker level, in which case main must be a static method in class/struct. But this is linker implementation dependent, not-portable and dangerous.

However, in the second situation you mentioned is a result of violation of One Definition Rule. You are defining a name (main()) more than once in a single translation unit.

You can not define a function twice, it works when you change the definition into a declaration inside the class/struct:

#include <iostream>

struct runtime_entry_point
{
    friend int main();
};

int main()
{
    std::cout << "Hello, world!" << std::endl;
}

This works just fine with GCC.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top