Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
144 views
in Technique[技术] by (71.8m points)

c++ - Why SDL defines main macro?

After having some trouble setting up SDL, I found out that SDL defines a macro that replaces main:

#define main SDL_main

// And then
extern C_LINKAGE int SDL_main(int argc, char *argv[]);

This can also create compilation errors, if the main function doesn't have the argc and argv parameters defined.

This macro gives me headaches just when I see it... Why does SDL need to redefine main? After some more searching, I found that some people #undef main, and use it the normal way.

So this is the question: why does SDL need to redefine main, what does it do? Are there any side effects to undefining it?

One thing I noticed is that SDL redirects standard output and error to files (and I don't want this behavior), and this behavior stops if I undefine main.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Per the SDL Windows FAQ:

You should be using main() instead of WinMain() even though you are creating a Windows application, because SDL provides a version of WinMain() which performs some SDL initialization before calling your main code.

If for some reason you need to use WinMain(), take a look at the SDL source code in src/main/win32/SDL_main.c to see what kind of initialization you need to do in your WinMain() function so that SDL works properly.

SDL requires initialization, so it injects its own main function that runs its initialization before calling your "main" function, which it renames to SDL_main so that it does not conflict with the actual main function. As noted in the FAQ, your main function must be of the form

int main(int argc, char* argv[])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...