Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using SDL2_gfx issues using C++

Tags:

c++

sdl

When I use SDL2_gfx with the common.c /common.h files that are included with it, and then use the cpp instead of c extension using VS201X, I get the LNK2019: unresolved external symbol _SDL_main

What that means is if I change the file containing main to test.c, it compiles. When I change it back to text.cpp it fails to compile. I think that indicates that it only works as C, and not C++.

Below is the code I copied from SDL2_gfxPrimitives.c (Spaces added so they would show up):

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <time.h>

#include "common.h"

#include "SDL2_gfxPrimitives.h"

static CommonState *state;

int main(int argc, char* argv[])
{
/* Initialize test framework */
state = CommonCreateState(argv, SDL_INIT_VIDEO);

return 1;
}

I need to use the library in C++ but it seems I don't know enough to figure out how. Any help would be appreciated, I've spent two days attempting to figure this out.

like image 508
Lance Zimmerman Avatar asked Jul 19 '26 16:07

Lance Zimmerman


1 Answers

This is a little bit of a gotcha for SDL.

What it does is #define main SDL_main

This renames int main(int argc, char *argv[]) into int SDL_main(int argc, char *argv[]).

In order to use it, SDL wants an unmangled SDL_main to link against, and because you simply renamed the test.c -> test.cpp, you didn't add the code to cause this to happen.

It's described in the documentation:

The application's main() function must be called with C linkage, and should be declared like this:

 #ifdef __cplusplus 
 extern "C" 
 #endif 
 int main(int argc, char *argv[]) 
 { 
 } 

so if you put the:

#ifdef __cplusplus
extern "C"
#endif

immediately before the declaration of the main function, it should link correctly.

like image 75
Petesh Avatar answered Jul 22 '26 07:07

Petesh