Search code examples
c++dlldynamic-library

C++: Implement custom Main function


WinMain is a function that 'replaces' the default main entry point 'main'.

The user can then define its main entry point like

int WINAPI WinMain(...) { }


How is this kind of encapsulation done?

Well, most likely, at some point it looks like this:

int main() // This must be defined somewhere in windows.h
{
    return WinMain(...);
}

Question: How can I accomplish such an encapsulation of my own, which then calls WinMain? Note: The library which I made is a DLL, so it will look like this:

// This is the minimal code for the application which uses 'MyLibrary'
#pragma comment(lib, "MyLibrary.lib")
include "MyLibrary.h"

void Main(MyCustomParameter *params)
{
    // Write user code here
}

The problem however is, that the DLL doesn't 'know' the Main() function and therefore throws an 'unresolved external symbol' compile error. So how can I encapsulate it like this?


Solution

  • You have to decide on a signature of your custom main function and declare it as "extern" (extern "C" in case of C++). Then, application code will have to define that function and link against your static library that has the actual _main entry point. For example:

    extern "C" int my_main(int argc, char *argv[]);
    
    int main(int argc, char *argv[])
    {
        return my_main(argc, argv);
    }