1

SDL has a WinMain in its implamentation and declares the SDL_main function. The User can define the body of that function and the entry point in SDL library calls that function.

I want to implement a library with that same implementation. So how do I build a library in c++ that contains the entry point and give to the user a prototype of a function to after be defined and be called like SDL does.

A possible implementation could be:

Lib.hpp:

#define Main lib_main
extern int lib_main ();

Lib.cpp:

#include "lib.hpp"

int main (){
    // the lib code runs here
    lib_main();
}

after build the this library I can use like so:

main.cpp

#include "lib.hpp"
int Main(){
    // The user code
}

I can't compile Lib.cpp with that command:

g++ -shared lib.cpp -o Lib.dll -Wl,--out-implib,libLib.a

it get me a undefined reference for the lib_main().

I'm using windows.

Mateus Sarmento
  • 153
  • 1
  • 7
  • `int Main(){...}` will expand as `int lib_main();(){...}` ... might want to update your `#define` in Lib.hpp – AJNeufeld Mar 29 '16 at 22:17
  • It is possible with build flags to [change the entry point of a program](http://stackoverflow.com/questions/7494244/how-to-change-entry-point-of-c-program-with-gcc) but other than that you've answered your own question. – Matt Mar 29 '16 at 22:35
  • Don't do it. SDL shouldn't do it either. It makes using several libraries together a huge pain in the ass for your users, and they will hate you. – Nikos C. Mar 30 '16 at 06:14

1 Answers1

3

You didn't specify your platform, but if you are using GCC, your code works.

Compile a static library like so:

g++ -c -o Lib.o Lib.cpp
ar rcs libLib.a Lib.o

Compile the main program like so:

g++ -L. -lLib -o main main.cpp

OR

Compile a shared library for *nix like so:

g++ -shared -o libLib.so Lib.cpp

Compile the main program like so:

g++ -L. -lLib -o main main.cpp

OR

Compile a shared library and an import library for Windows like so:

g++ -shared -o libLib.dll --Wl,--out-implib,libLib_dll.a Lib.cpp

Compile the main program like so, linking against the import library and adding the current directory to the runtime search path:

g++ -L. -lLib_dll -Wl,-rpath,. -o main main.cpp
Chaos
  • 335
  • 1
  • 6
  • Thanks for answer. I have try and it works. But here is the thing. When I do these commands to create the shared and static libraries: g++ -c Lib.cpp g++ -shared -o Lib.dll Lib.o -Wl,--out-implib,libLib.a g++ main.cpp -o main -L. -lLib It just compile the .a and the actual main program but doesn't the .dll. The program can't execute because there isn't a dll file. Did you know the difference? – Mateus Sarmento Mar 29 '16 at 23:14
  • It looks like you are trying to build both static and shared libraries. Make sure you are not confusing the static library with the import library for the shared library. Check my updated answer. – Chaos Mar 30 '16 at 05:31