Question

So I can successfully change the C++ entry point to be in a class, which helps me isolate my graphics system initialization from the main program code. But when I call some library code from the new main the whole program crashes. For example:

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

I compile it with these linker options: -e__Z5ENTRYv -nostartfiles
Without the /cout/ line it works fine, else it crashes with /Access Violation/ at

enter image description here

Is there something that I'm missing?

Was it helpful?

Solution

What exactly do you think -nostartfiles does?

It suppresses the CRT initialization, which among other things is responsible for calling global constructors. Without global constructors, cout isn't initialized. Without initialization, your program goes boom.

Why mess with this anyway? Wouldn't it be easier to just link in a small boilerplate main? It could look like this:

// 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(); }

Now just derive your main class from App and add a global object of that type.

OTHER TIPS

In C++, main is a magic function; the compiler can generate extra code in it to, for example, initialize static variables. Or, depending on the implementation, this may be done by the startup code. In either case, setting some other global symbol as entry point will probably mean that static variables will not be initialized. Don't do it: changing the entry point like this is really only valid if you use no static variables, anywhere, and even then, it's shaky.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top