【问题标题】:How to call main function from another header files cpp file如何从另一个头文件cpp文件中调用main函数
【发布时间】:2019-07-13 15:52:16
【问题描述】:

我想从另一个头文件 cpp 文件中调用 main 函数。其中main 包含一个头文件。 让我们调用 main.cpp 有一个头文件。我可以从头文件 cpp 中调用 main.cpp 的 main 吗?

这是 main.cpp

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

这是另一个.h

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

这是另一个_func.cpp 单独文件

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

【问题讨论】:

  • C++ 标准禁止调用main:C++ 2017 (draft N4659) 6.6.1 [basic.start.main] 3 说“函数main 不得在程序中使用……”
  • 对不起,我是 C++ 新手,所以请用简单的英语解释一下
  • main() 中唯一的内容是对其他函数的函数调用。只需从另一个文件中调用它。有关详细信息,请参阅您的 C++ 书籍。

标签: c++ header-files main


【解决方案1】:

C++ 标准不允许在您自己的代码中调用main。如果你这样做了,你就处于未定义行为领域,你的整个程序毫无意义。

只有实现可以调用main 作为程序的入口点。

【讨论】:

    【解决方案2】:

    main 的特殊之处在于它不能被调用(包括从自身内部),它的地址不能被获取等等。

    所以你最好用类似的东西

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

    这是另一个.h

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

    这是另一个_func.cpp 单独文件

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

    【讨论】:

    • 当我从another::another_func(void) 调用Main() 时,错误显示像这样Main() 未在此范围内声明
    • 看起来编译器没有意识到这一点。所以声明吧。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-15
    • 1970-01-01
    • 2015-01-30
    • 1970-01-01
    • 2020-03-21
    • 2016-03-11
    相关资源
    最近更新 更多