Directory Title
- common mistakes
-
- Detailed error report
- solution
- Analyze the reason
-
- About the initialization of SDL
- No problem in theory, why are warnings often reported?
- SDL main function related source code
- Conclusion
Common mistakes
Detailed error report
SDL/include/SDL_main.h:143: warning: "main" redefined 143 | #define main SDL_main
Solution
This problem is due to the definition of a macro named main
in the SDL_main.h
file in the SDL library, which is different from the main
in your program > function conflicts.
You can try the following solutions:
-
Make sure to
#define SDL_MAIN_HANDLED
before including any SDL header files. This is because theSDL_MAIN_HANDLED
macro needs to be defined before includingSDL.h
orSDL_main.h
to prevent themain
macro Definition. Your code should look like this:#define SDL_MAIN_HANDLED #include "SDL.h"
-
If the above still doesn’t solve the problem, you can try undefining the
main
macro immediately after including the SDL header file:#include "SDL.h" #undef main
This ensures that in your code, main
is no longer overridden by SDL macro definitions.
Analysis reason
Normally, a program can have only one main
function. However, SDL uses a trick of renaming the user’s main
function to SDL_main
via a macro definition, and then providing its own main
function. That way, when you write the main
function in your code, the preprocessor will actually rename it to SDL_main
.
Here is the macro defined in SDL’s SDL_main.h
header file:
#define main SDL_main
This means that when you write the following main
function in your code:
int main(int argc, char* argv[]) { // your code }
The preprocessor will actually convert this to:
int SDL_main(int argc, char* argv[]) { // your code }
Then, SDL provides its own main
function, which will do some initialization work first, and then call SDL_main
(that is, your main
function ), and finally clean up.
If you don’t want SDL to redefine your main
function, you can define the SDL_MAIN_HANDLED
macro before including the SDL header file, and then in your main
Manually call the initialization and cleanup functions of SDL in the function.
About SDL initialization
We already know that SDL will call its own main function through macros, so what does it do?
Specifically, SDL’s main
function usually does the following things:
- Initialize the SDL library: This includes initializing the video subsystem, audio subsystem, event subsystem, etc.
- Calling the user’s
main
function: After initialization, SDL’smain
function callsSDL_main
(which is the user’smain
code> function). - Clean up SDL library: After the user’s
main
function returns, SDL’smain
function will clean up the SDL library, including closing the video subsystem, audio subsystem, event subsystem, etc.
This design allows SDL to insert its own code before and after the execution of the user’s main
function without requiring the user to explicitly call SDL’s Initialization and cleanup functions.
No problem in theory, why are warnings often reported?
In Qt, the main
function is usually used to create a QApplication
object and start Qt’s event loop. When SDL tries to redefine the main
function via a macro definition, this may cause Qt’s initialization code to be incorrectly placed in the SDL_main
function instead of the real >main
function, causing problems.
In addition, Qt’s moc (Meta-Object Compiler) may also warn about redefinition of the main
macro. moc is a Qt tool for working with Qt’s meta-object system. It scans the source code for class definitions, looking for classes that use Qt features such as signals and slots, and generates additional code for these classes. moc may generate warnings when processing source code if main
is defined as a macro.
Therefore, if you use SDL in your Qt program, the best practice is to define the SDL_MAIN_HANDLED
macro before including the SDL header file, and then manually call it in your main
function Initialization and cleanup functions for SDL. This avoids redefinition of the main
macro, while ensuring both Qt and SDL initialization code is in the correct place.
SDL main function related source code
/* SDL_windows_main.c, placed in the public domain by Sam Lantinga 4/13/98 The WinMain function -- calls your program's main() function */ #include "SDL_config.h" #ifdef __WIN32__ /* Include this so we define UNICODE properly */ #include "../../core/windows/SDL_windows.h" #include <shellapi.h> /* CommandLineToArgvW() */ /* Include the SDL main definition header */ #include "SDL.h" #include "SDL_main.h" #ifdef main #undef main #endif /* main */ /* Pop up an out of memory message, returns to Windows */ static BOOL OutOfMemory(void) {<!-- --> SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Fatal Error", "Out of memory - aborting", NULL); return FALSE; } #if defined(_MSC_VER) /* The VC++ compiler needs main/wmain defined */ #define console_ansi_main main #if UNICODE #define console_wmain wmain #endif #endif /* Gets the arguments with GetCommandLine, converts them to argc and argv and calls SDL_main */ static int main_getcmdline(void) {<!-- --> LPWSTR *argvw; char **argv; int i, argc, result; argvw = CommandLineToArgvW(GetCommandLineW(), & argc); if (argvw == NULL) {<!-- --> return OutOfMemory(); } /* Note that we need to be careful about how we allocate/free memory here. * If the application calls SDL_SetMemoryFunctions(), we can't rely on * SDL_free() to use the same allocator after SDL_main() returns. */ /* Parse it into argv and argc */ argv = (char **)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, (argc + 1) * sizeof(*argv)); if (argv == NULL) {<!-- --> return OutOfMemory(); } for (i = 0; i < argc; + + i) {<!-- --> DWORD len; char *arg = WIN_StringToUTF8W(argvw[i]); if (arg == NULL) {<!-- --> return OutOfMemory(); } len = (DWORD)SDL_strlen(arg); argv[i] = (char *)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, (size_t)len + 1); if (!argv[i]) {<!-- --> return OutOfMemory(); } SDL_memcpy(argv[i], arg, len); SDL_free(arg); } argv[i] = NULL; LocalFree(argvw); SDL_SetMainReady(); /* Run the application main() code */ result = SDL_main(argc, argv); /* Free argv, to avoid memory leak */ for (i = 0; i < argc; + + i) {<!-- --> HeapFree(GetProcessHeap(), 0, argv[i]); } HeapFree(GetProcessHeap(), 0, argv); return result; } /* This is where execution begins [console apps, ansi] */ int console_ansi_main(int argc, char *argv[]) {<!-- --> return main_getcmdline(); } #if UNICODE /* This is where execution begins [console apps, unicode] */ int console_wmain(int argc, wchar_t *wargv[], wchar_t *wenvp) {<!-- --> return main_getcmdline(); } #endif /* This is where execution begins [windowed apps] */ int WINAPI MINGW32_FORCEALIGN WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR szCmdLine, int sw) /* NOLINT(readability-inconsistent-declaration-parameter-name) */ {<!-- --> return main_getcmdline(); } #endif /* __WIN32__ */ /* vi: set ts=4 sw=4 expandtab: */
/* Simple Direct Media Layer Copyright (C) 1997-2023 Sam Lantinga <[email protected]> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages emerging from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be Appreciated but not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef SDL_main_h_ #define SDL_main_h_ #include "SDL_stdinc.h" /** * \file SDL_main.h * * Redefine main() on some platforms so that it is called by SDL. */ #ifndef SDL_MAIN_HANDLED #if defined(__WIN32__) /* On Windows SDL provides WinMain(), which parses the command line and passes the arguments to your main function. If you provide your own WinMain(), you may define SDL_MAIN_HANDLED */ #define SDL_MAIN_AVAILABLE #elif defined(__WINRT__) /* On WinRT, SDL provides a main function that initializes CoreApplication, creating an instance of IFrameworkView in the process. Please note that #include'ing SDL_main.h is not enough to get a main() function working. In non-XAML apps, the file, src/main/winrt/SDL_WinRT_main_NonXAML.cpp, or a copy of it, must be compiled into the app itself. In XAML apps, the function, SDL_WinRTRunApp must be called, with a pointer to the Direct3D-hosted XAML control passed in. */ #define SDL_MAIN_NEEDED #elif defined(__GDK__) /* On GDK, SDL provides a main function that initializes the game runtime. Please note that #include'ing SDL_main.h is not enough to get a main() function working. You must either link against SDL2main or, if not possible, call the SDL_GDKRunApp function from your entry point. */ #define SDL_MAIN_NEEDED #elif defined(__IPHONEOS__) /* On iOS SDL provides a main function that creates an application delegate and starts the iOS application run loop. If you link with SDL dynamically on iOS, the main function can't be in a shared library, so you need to link with libSDLmain.a, which includes a stub main function that calls into the shared library to start execution. See src/video/uikit/SDL_uikitappdelegate.m for more details. */ #define SDL_MAIN_NEEDED #elif defined(__ANDROID__) /* On Android SDL provides a Java class in SDLActivity.java that is the main activity entry point. See docs/README-android.md for more details on extending that class. */ #define SDL_MAIN_NEEDED /* We need to export SDL_main so it can be launched from Java */ #define SDLMAIN_DECLSPEC DECLSPEC #elif defined(__NACL__) /* On NACL we use ppapi_simple to set up the application helper code, then wait for the first PSE_INSTANCE_DIDCHANGEVIEW event before starting the user main function. All user code is run in a separate thread by ppapi_simple, thus allowing for blocking io to take place via nacl_io */ #define SDL_MAIN_NEEDED #elif defined(__PSP__) /* On PSP SDL provides a main function that sets the module info, activates the GPU and starts the thread required to be able to exit the software. If you provide this yourself, you may define SDL_MAIN_HANDLED */ #define SDL_MAIN_AVAILABLE #elif defined(__PS2__) #define SDL_MAIN_AVAILABLE #define SDL_PS2_SKIP_IOP_RESET() \ void reset_IOP(); \ void reset_IOP() {<!-- -->} #elif defined(__3DS__) /* On N3DS, SDL provides a main function that sets up the screens and storage. If you provide this yourself, you may define SDL_MAIN_HANDLED */ #define SDL_MAIN_AVAILABLE #endif #endif /* SDL_MAIN_HANDLED */ #ifndef SDLMAIN_DECLSPEC #define SDLMAIN_DECLSPEC #endif /** * \file SDL_main.h * * The application's main() function must be called with C linkage, * and should be declared like this: * \code * #ifdef __cplusplus * extern "C" * #endif * int main(int argc, char *argv[]) * { * } * \endcode */ #if defined(SDL_MAIN_NEEDED) || defined(SDL_MAIN_AVAILABLE) #define main SDL_main #endif #include "begin_code.h" #ifdef __cplusplus extern "C" {<!-- --> #endif /** * The prototype for the application's main() function */ typedef int (*SDL_main_func)(int argc, char *argv[]); extern SDLMAIN_DECLSPEC int SDL_main(int argc, char *argv[]); /** * Circumvent failure of SDL_Init() when not using SDL_main() as an entry * point. * * This function is defined in SDL_main.h, along with the preprocessor rule to * redefine main() as SDL_main(). Thus to ensure that your main() function * will not be changed it is necessary to define SDL_MAIN_HANDLED before * including SDL.h. * * \since This function is available since SDL 2.0.0. * * \sa SDL_Init */ extern DECLSPEC void SDLCALL SDL_SetMainReady(void); #if defined(__WIN32__) || defined(__GDK__) /** * Register a win32 window class for SDL's use. * * This can be called to set the application window class at startup. It is * safe to call this multiple times, as long as every call is eventually * paired with a call to SDL_UnregisterApp, but a second registration attempt * while a previous registration is still active will be ignored, other than * to increment a counter. * * Most applications do not need to, and should not, call this directly; SDL * will call it when initializing the video subsystem. * * \param name the window class name, in UTF-8 encoding. If NULL, SDL * currently uses "SDL_app" but this isn't guaranteed. * \param style the value to use in WNDCLASSEX::style. If `name` is NULL, SDL * currently uses `(CS_BYTEALIGNCLIENT | CS_OWNDC)` regardless of * what is specified here. * \param hInst the HINSTANCE to use in WNDCLASSEX::hInstance. If zero, SDL * will use `GetModuleHandle(NULL)` instead. * \returns 0 on success, -1 on error. SDL_GetError() may have details. * * \since This function is available since SDL 2.0.2. */ extern DECLSPEC int SDLCALL SDL_RegisterApp(const char *name, Uint32 style, void *hInst); /** * Deregister the win32 window class from an SDL_RegisterApp call. * * This can be called to undo the effects of SDL_RegisterApp. * * Most applications do not need to, and should not, call this directly; SDL * will call it when deinitializing the video subsystem. * * It is safe to call this multiple times, as long as every call is eventually * paired with a prior call to SDL_RegisterApp. The window class will only be * deregistered when the registration counter in SDL_RegisterApp decrements to * zero through calls to this function. * * \since This function is available since SDL 2.0.2. */ extern DECLSPEC void SDLCALL SDL_UnregisterApp(void); #endif /* defined(__WIN32__) || defined(__GDK__) */ #ifdef __WINRT__ /** * Initialize and launch an SDL/WinRT application. * * \param mainFunction the SDL app's C-style main(), an SDL_main_func * \param reserved reserved for future use; should be NULL * \returns 0 on success or -1 on failure; call SDL_GetError() to retrieve * more information on the failure. * * \since This function is available since SDL 2.0.3. */ extern DECLSPEC int SDLCALL SDL_WinRTRunApp(SDL_main_func mainFunction, void * reserved); #endif /* __WINRT__ */ #if defined(__IPHONEOS__) /** * Initializes and launches an SDL application. * * \param argc The argc parameter from the application's main() function * \param argv The argv parameter from the application's main() function * \param mainFunction The SDL app's C-style main(), an SDL_main_func * \return the return value from mainFunction * * \since This function is available since SDL 2.0.10. */ extern DECLSPEC int SDLCALL SDL_UIKitRunApp(int argc, char *argv[], SDL_main_func mainFunction); #endif /* __IPHONEOS__ */ #ifdef __GDK__ /** * Initialize and launch an SDL GDK application. * * \param mainFunction the SDL app's C-style main(), an SDL_main_func * \param reserved reserved for future use; should be NULL * \returns 0 on success or -1 on failure; call SDL_GetError() to retrieve * more information on the failure. * * \since This function is available since SDL 2.24.0. */ extern DECLSPEC int SDLCALL SDL_GDKRunApp(SDL_main_func mainFunction, void *reserved); /** * Callback from the application to let the suspend continue. * * \since This function is available since SDL 2.28.0. */ extern DECLSPEC void SDLCALL SDL_GDKSuspendComplete(void); #endif /* __GDK__ */ #ifdef __cplusplus } #endif #include "close_code.h" #endif /* SDL_main_h_ */ /* vi: set ts=4 sw=4 expandtab: */
Conclusion
In our programming learning journey, understanding is an important step to take us to the next level. However, mastering new skills and ideas always takes time and persistence. From a psychological point of view, learning is often accompanied by continuous trial and error and adjustment, which is like our brain gradually optimizing its “algorithm” for solving problems.
This is why when we encounter mistakes, we should see them as opportunities to learn and improve, not just obsessions. By understanding and solving these problems, we can not only fix the current code, but also improve our programming ability and prevent the same mistakes from being made in future projects.
I encourage everyone to actively participate and continuously improve their programming skills. Whether you are a beginner or an experienced developer, I hope my blog can help you in your learning journey. If you find this article useful, please click to bookmark it, or leave your comments to share your insights and experiences. You are also welcome to make suggestions and questions about the content of my blog. Every like, comment, share and follow is the greatest support for me and the motivation for me to continue to share and create.
Read my CSDN homepage to unlock more exciting content: Bubble’s CSDN homepage