简体   繁体   English

如何从另一个头文件cpp文件调用main函数

[英]How to call main function from another header files cpp file

I want to call main function form another header files cpp file.我想从另一个头文件 cpp 文件中调用main函数。 where main included a header file.其中main包含一个头文件。 let's call main.cpp has a header file.让我们调用 main.cpp 有一个头文件。 can I call main.cpp's main from header files cpp?我可以从头文件 cpp 调用 main.cpp 的main吗?

This is main.cpp这是 main.cpp

    #include "another.h"
    int main()
    {
        cout<<"Main";
    }

this is another.h这是另一个.h

   class another
    {
       public:
               void another_func(void);
    };

this is another_func.cpp separate file这是 another_func.cpp 单独文件

    void another::another_func(void)
    {
       //how do i call main()
    }

Calling main in your own code is not allowed by the C++ standard. C++ 标准不允许在您自己的代码中调用main If you do, you are in Undefined Behaviour land and your entire program is meaningless.如果你这样做了,你就处于未定义行为领域,你的整个程序毫无意义。

Only the implementation may call main as an entry point to your program.只有实现可以调用main作为程序的入口点。

main is special in that it cannot be called (including from inside itself), its address cannot be taken etc. main的特殊之处在于它不能被调用(包括从内部调用),它的地址不能被获取等。

So you're better off with something like所以你最好使用类似的东西

#include "another.h"
int main()
{
    return Main();
}
int Main() {
    std::cout<<"Main\n";
    return 0;
}

this is another.h这是另一个.h

class another
{
   public:
           void another_func(void);
};

this is another_func.cpp separate file这是 another_func.cpp 单独文件

void another::another_func(void)
{
    Main();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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