gpt4 book ai didi

c++ - 更改 C++ 程序入口点。 STL 崩溃

转载 作者:太空狗 更新时间:2023-10-29 23:51:47 24 4
gpt4 key购买 nike

所以我可以成功地将 C++ 入口点更改为一个类,这有助于我将图形系统初始化与主程序代码隔离开来。但是当我从新的 main 调用一些库代码时,整个程序崩溃了。例如:

#include <iostream>
using namespace std;
int ENTRY(){
cout << "hello from here" << endl;
system("pause");
}

我使用这些链接器选项编译它:-e__Z5ENTRYv -nostartfiles
没有/cout/行它工作正常,否则它会因/Access Violation/at

而崩溃

enter image description here

有什么我想念的吗?

最佳答案

您认为 -nostartfiles 的具体作用是什么?

它抑制了 CRT 初始化,其中负责调用全局构造函数。没有全局构造函数,cout 不会被初始化。如果不进行初始化,您的程序就会运行良好。

为什么要搞砸这个呢?只链接一个小样板 main 不是更容易吗?它可能看起来像这样:

// app.hpp
class App {
protected:
App();
virtual ~App();
private:
virtual int run(/*args if you want them*/) = 0;
int startup(/*args if you want them*/);
friend int app_run(/*args if you want them*/);
};

// app.cpp: just add this to your project
namespace { App* the_app; }
App::App() { the_app = this; }
App::~App() {}

int App::startup() {
// Add whatever code you want here, e.g. to create a window.
return run();
}

int app_run() { return the_app->startup(); }

int main() { return app_run(); }
int wmain() { return app_run(); }
int WinMain(HINSTANCE, HINSTANCE, char*, int) { return app_run(); }
int wWinMain(HINSTANCE, HINSTANCE, WCHAR*, int) { return app_run(); }

现在只需从 App 派生主类并添加该类型的全局对象。

关于c++ - 更改 C++ 程序入口点。 STL 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18854270/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com