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.
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[])
While I agree that it's a strange practice, there are situations where this is a reasonable solution, though it largely depends on the platform. Consider that different platforms have different entry points. Windows is typically WinMain, Linux is main, interacting with Android happens in Java, WinRT uses C++/CX extensions, and so on. Program entry point and APIs can be very platform specific and SDL tries to save you the trouble of having to deal with this. If you're only targeting Windows and SDL is only there to save you the trouble of working with WIN32 API, you might not need it. But if you ever go beyond desktop, you'll find it useful in my opinion.
Related
I start learning VC++/MFC. then I created a "HelloWord" program,
I got two App.h/.cpp AppDlg.h/.cpp basic files by created a basic Dialog project.
The first problem: I can't find the program entry. there is no main.cpp in the project.
Then I tried to find the relationship between App and AppDlg, met the second problem: base on the file name, looks like AppDlg should be a customized MFC Dialog component, and the App supposes to be the main event thread. But I got below in both .cpp files. it included each other. I thought AppDlg should be the part of App.
#include "App.h"
#include "AppDlg.h"
these two problem makes me confused about the structure of the project.
Why MFC code looks so different? For what purpose do like this?
The reason you don't have a "main" function (quoted because it's not actually called main(a)) is because the code has already been written for you. This is quite common in frameworks, where a certain amount of set-up is done before the code you're responsible for actually starts running.
In fact, this is often the case even for situations where you do create a main(), since there's usually start-up code that's responsible for doing things like turning the arguments into argc/argc objects to hand over to your main code (if you ever see an object file like crt0.o or ucrt.lib, that's probably the C run-time start-up code).
In the early days of Windows, the code you wrote had a WinMain() function(a) which was called by the start-up code in lieu of main(), and it was typically responsible for registering window classes, creating and starting message pumps, and all sorts of other stuff which is usually identical in every application. So, by moving that work to a framework of some description, it greatly reduces the amount of code you need to write.
In terms of how this works, think of what would happen if the stuff you linked to contained the following:
int main(int argc, char *argv[]) {
return bob(argc, argv);
}
Then your code would not actually need a main() function at all. It would need a bob() function of course and that's very similar to the situation you've discovered: Microsoft has written their own "main" function in the MFC framework which sets up things so that MFC will work.
Admittedly, my bob-based framework doesn't provide as much benefit as MFC but it's only meant to be an example of how it can be done :-)
In terms of what goes into each file created by each project type, this link may help. For example, the two files you mentioned are covered by:
<projname>.h : the main include file for the program or DLL. It contains all global symbols and #include directives for other header files. It derives the C<projname>App class from CWinApp and declares an InitInstance member function. For a control, the C<projname>App class is derived from COleControlModule.
<projname>dlg.cpp and <projname>dlg.h : created if you choose a dialog-based application. The files derive and implement the dialog class, named C<projname>Dlg, and include skeleton member functions to initialise a dialog and perform dialog data exchange (DDX). Your About dialog class is also placed in these files instead of in <projname>.cpp.
Note that there's nothing in those descriptions about a message pump (for example). That's because all the heavy lifting for that is included in the base classes for the things that are created.
(a) The reason why it *wasn't main() can be found in this article on The Old New Thing - it was basically to ensure no clash between what the language supplied and what Windows needed.
From the books i have read about C and C++ I understood that the entry point in C program must be main.Till now i had made only console applications and now im starting to learn about windows applications. So my questions is :
Why the entry point in Win32 project is not main (but WinMain) and how is it possible to be different ( maybe main calls WinMain ?) ?
ps. Sorry for bad english
It is true that C++ requires main to be the "entrypoint" of the program, at least under what's called "hosted implementations" (the ones you're probably using). This is why you get a linker error with GCC if you forgot to define a main.
However, in practice, the gap where your program ends and the "runtime" begins, makes things seem a little more wooly — when your program is launched, the first functions called are actually inside the runtime, which will eventually get around to invoking main. It is actually this invocation which causes the linker error if you forgot to define a main.
Microsoft has decided that, for Windows GUI programs, instead of invoking main, their runtime will invoke WinMain. As a consequence, you have to define a function WinMain for it to find, instead of main. Technically this violates the C++ standard, but it works because Microsoft makes it work.
The actual name and signature of the entry point in your code is dictated by the runtime framework you decide to use inside your EXE.
When the OS executes an EXE, it first calls an entry point specified in the EXE header by the linker, and is usually located in the compiler vendor's runtime library.
The runtime library's entry point initializes the library, sets up globals, etc, and then finally calls an entry point that your code must implement (the runtime library contains a reference to an external entry point, and the linker hooks up your code's entry point to that reference).
So, your code's entry point is whatever the runtime library requires it to be. The standard entry point for console apps in C/C++ is main, and the traditional entry point for Windows GUI apps is WinMain. But this is not a requirement as far as the OS is concerned.
In fact main is just a name look at assembly language: you are free to declare your Entry Point as you want eg:
.code
START:
ret
END START
But in C++ it doesn't allow you to define your own EP. So must implement the convention: for console you need main, wmain, win32: WinMain, for Dll: dllmain...
I have simple C++ programm:
#include <iostream>
using namespace std;
void main()
{
cout << "Hello, world, from Visual C++!" << endl;
}
Compiled with following command: cl /EHsc hello.cpp
I want to start debugging of executable, How can I find this main function's corresponding assembly code in the debugger? (I'm using x64dbg)
Entry point is not same as Main function.
I found main function and it is somewhere not near with Entry Point, I had strings and I found this easily.
Is there any way or rule or best practise how to guess where is main's corresponding assmebly code?
EDIT:
I have source code, but I just learning RE.
Although the entry point is usually not the main defined in your executable, this is merely because it is quite common for compilers to to wrap main with some initialization code.
In most cases the initialization code is quite similar and has one of few versions per compiler. Most of those functions have an IDA FLIRT signature, and opening the binary with IDA will define an WinMain, main, etc function for you automatically. You can also use free (trial) versions of IDA for that.
If that's not the case, it's pretty straight forward to get from the entrypoint to the main, by following the few calls inside the entrypoint function one level deep. the main call is usually near the end of the entrypoint function.
Here's an example, main function is selected near the bottom (Note this is a unix executable compiled for windows using mingw, so this is somewhat different from most native win32 executables).
if you debugging own code - the best way to stop somewhere under debugger - use next code
if (IsDebuggerPresent()) __debugbreak();
so you can insert it at begin of your main or any other places.
if you debugging not own binary code - binary can at all not containing c/c++ CRT code - so question became senseless. however if CRT code exist, despite many different implementations - all use common patterns and after some practice - possible found where CRT code call main.
in case standard windows binaries, for which exist pdb files - this is not a problem at all
Generally, you can't.
When you compile a program, you get a binary and (optionally) debugging symbols.
If you have the debugging symbols, let IDA or your debugger load them, and then you should be able to symbolically evaluate main to the address of the function (e.g in IDA, just press g and write main and you'll be there. In WinDbg or gdb you can type b main)
However, the more common case would be to find the main function on a binary for which you do not posses the debugging symbols. In this case, you don't know where the main function is, nor if it is even there. The binary may not use the common libc practice of an entry point doing initialization and then calling main(int argc, char *argv[], char *envp[]).
But because you're an intelligent human, I'd recommended reading the libc implementation for the compiler/platform you think you're working with, and follow the logic from the platform-defined entry point until you see the call main instruction.
(Please note that .NET binaries and other types of binaries may behave completely differently.)
#include <gl/freeglut.h>
void Keyboard(int value){
glutTimerFunc(33,Keyboard,0);
}
int main(int argc, char **argv){
glutTimerFunc(33,Keyboard);
}
Is there any way to pass data from the main function to the keyboard function without having to use global variables? It seems like the function glutTimerFunc only allows functions with the signature (int value) which seems very restrictive.
so is there another way to get the data into another funcion without having them to be global?
Like other people already suggested: Don't use GLUT. GLUT never was meant to be the foundation of serious application. It's a small framework meant for small OpenGL tech demos. The problem you're running into is that C and C++ lack a concept called "closures", or sometimes also called "delegates". Other languages have them and in fact when you use the GLUT bindings in those languages you don't experience the problem.
Since C/C++'s lack of closures is so prominent a small library (that does crazy but genius things internally) has been written, that allows it, to create closures in C. It's called ffcall, unfortunately seems to be unmaintained, but is in use by projects as the GNU Common Lisp and Scheme compilers.
I wrote about using ffcall already in the StackOverflow answers https://stackoverflow.com/a/8375672/524368 and https://stackoverflow.com/a/10207698/524368
You can use a trick: pass a pointer to the object as value, after casting it to int:
i instance;
keyboard((int)&i);
If you need to call the function with the timer, consider the fact that when a function ends all the object in the stack are deallocated. So in this case you should allocate the object with new, and always have a handle to it in the case you need to deallocate it.
It's very tricky, I know. If you can switch to another library do it.
From what I can tell you can kick off all the action in a constructor when you create a global object. So do you really need a main() function in C++ or is it just legacy?
I can understand that it could be considered bad practice to do so. I'm just asking out of curiosity.
If you want to run your program on a hosted C++ implementation, you need a main function. That's just how things are defined. You can leave it empty if you want of course. On the technical side of things, the linker wants to resolve the main symbol that's used in the runtime library (which has no clue of your special intentions to omit it - it just still emits a call to it). If the Standard specified that main is optional, then of course implementations could come up with solutions, but that would need to happen in a parallel universe.
If you go with the "Execution starts in the constructor of my global object", beware that you set yourself up to many problems related to the order of constructions of namespace scope objects defined in different translation units (So what is the entry point? The answer is: You will have multiple entry points, and what entry point is executed first is unspecified!). In C++03 you aren't even guaranteed that cout is properly constructed (in C++0x you have a guarantee that it is, before any code tries to use it, as long as there is a preceeding include of <iostream>).
You don't have those problems and don't need to work around them (wich can be very tricky) if you properly start executing things in ::main.
As mentioned in the comments, there are however several systems that hide main from the user by having him tell the name of a class which is instantiated within main. This works similar to the following example
class MyApp {
public:
MyApp(std::vector<std::string> const& argv);
int run() {
/* code comes here */
return 0;
};
};
IMPLEMENT_APP(MyApp);
To the user of this system, it's completely hidden that there is a main function, but that macro would actually define such a main function as follows
#define IMPLEMENT_APP(AppClass) \
int main(int argc, char **argv) { \
AppClass m(std::vector<std::string>(argv, argv + argc)); \
return m.run(); \
}
This doesn't have the problem of unspecified order of construction mentioned above. The benefit of them is that they work with different forms of higher level entry points. For example, Windows GUI programs start up in a WinMain function - IMPLEMENT_APP could then define such a function instead on that platform.
Yes! You can do away with main.
Disclaimer: You asked if it were possible, not if it should be done. This is a totally un-supported, bad idea. I've done this myself, for reasons that I won't get into, but I am not recommending it. My purpose wasn't getting rid of main, but it can do that as well.
The basic steps are as follows:
Find crt0.c in your compiler's CRT source directory.
Add crt0.c to your project (a copy, not the original).
Find and remove the call to main from crt0.c.
Getting it to compile and link can be difficult; How difficult depends on which compiler and which compiler version.
Added
I just did it with Visual Studio 2008, so here are the exact steps you have to take to get it to work with that compiler.
Create a new C++ Win32 Console Application (click next and check Empty Project).
Add new item.. C++ File, but name it crt0.c (not .cpp).
Copy contents of C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\crt\src\crt0.c and paste into crt0.c.
Find mainret = _tmain(__argc, _targv, _tenviron); and comment it out.
Right-click on crt0.c and select Properties.
Set C/C++ -> General -> Additional Include Directories = "C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\crt\src".
Set C/C++ -> Preprocessor -> Preprocessor Definitions = _CRTBLD.
Click OK.
Right-click on the project name and select Properties.
Set C/C++ -> Code Generation -> Runtime Library = Multi-threaded Debug (/MTd) (*).
Click OK.
Add new item.. C++ File, name it whatever (app.cpp for this example).
Paste the code below into app.cpp and run it.
(*) You can't use the runtime DLL, you have to statically link to the runtime library.
#include <iostream>
class App
{
public: App()
{
std::cout << "Hello, World! I have no main!" << std::endl;
}
};
static App theApp;
Added
I removed the superflous exit call and the blurb about lifetime as I think we're all capable of understanding the consequences of removing main.
Ultra Necro
I just came across this answer and read both it and John Dibling's objections below. It was apparent that I didn't explain what the above procedure does and why that does indeed remove main from the program entirely.
John asserts that "there is always a main" in the CRT. Those words are not strictly correct, but the spirit of the statement is. Main is not a function provided by the CRT, you must add it yourself. The call to that function is in the CRT provided entry point function.
The entry point of every C/C++ program is a function in a module named 'crt0'. I'm not sure if this is a convention or part of the language specification, but every C/C++ compiler I've come across (which is a lot) uses it. This function basically does three things:
Initialize the CRT
Call main
Tear down
In the example above, the call is _tmain but that is some macro magic to allow for the various forms that 'main' can have, some of which are VS specific in this case.
What the above procedure does is it removes the module 'crt0' from the CRT and replaces it with a new one. This is why you can't use the Runtime DLL, there is already a function in that DLL with the same entry point name as the one we are adding (2). When you statically link, the CRT is a collection of .lib files, and the linker allows you to override .lib modules entirely. In this case a module with only one function.
Our new program contains the stock CRT, minus its CRT0 module, but with a CRT0 module of our own creation. In there we remove the call to main. So there is no main anywhere!
(2) You might think you could use the runtime DLL by renaming the entry point function in your crt0.c file, and changing the entry point in the linker settings. However, the compiler is unaware of the entry point change and the DLL contains an external reference to a 'main' function which you're not providing, so it would not compile.
Generally speaking, an application needs an entry point, and main is that entry point. The fact that initialization of globals might happen before main is pretty much irrelevant. If you're writing a console or GUI app you have to have a main for it to link, and it's only good practice to have that routine be responsible for the main execution of the app rather than use other features for bizarre unintended purposes.
Well, from the perspective of the C++ standard, yes, it's still required. But I suspect your question is of a different nature than that.
I think doing it the way you're thinking about would cause too many problems though.
For example, in many environments the return value from main is given as the status result from running the program as a whole. And that would be really hard to replicate from a constructor. Some bit of code could still call exit of course, but that seems like using a goto and would skip destruction of anything on the stack. You could try to fix things up by having a special exception you threw instead in order to generate an exit code other than 0.
But then you still run into the problem of the order of execution of global constructors not being defined. That means that in any particular constructor for a global object you won't be able to make any assumptions about whether or not any other global object yet exists.
You could try to solve the constructor order problem by just saying each constructor gets its own thread, and if you want to access any other global objects you have to wait on a condition variable until they say they're constructed. That's just asking for deadlocks though, and those deadlocks would be really hard to debug. You'd also have the issue of which thread exiting with the special 'return value from the program' exception would constitute the real return value of the program as a whole.
I think those two issues are killers if you want to get rid of main.
And I can't think of a language that doesn't have some basic equivalent to main. In Java, for example, there is an externally supplied class name who's main static function is called. In Python, there's the __main__ module. In perl there's the script you specify on the command line.
If you have more than one global object being constructed, there is no guarantee as to which constructor will run first.
If you are building static or dynamic library code then you don't need to define main yourself, but you will still wind up running in some program that has it.
If you are coding for windows, do not do this.
Running your app entirely from within the constructor of a global object may work just fine for quite awhile, but sooner or later you will make a call to the wrong function and end up with a program that terminates without warning.
Global object constructors run during the startup of the C runtime.
The C runtime startup code runs during the DLLMain of the C runtime DLL
During DLLMain, you are holding the DLL loader lock.
Tring to load another DLL while already holding the DLL loader lock results in a swift death for your process.
Compiling your entire app into a single executable won't save you - many Win32 calls have the potential to quietly load system DLLs.
There are implementations where global objects are not possible, or where non-trivial constructors are not possible for such objects (especially in the mobile and embedded realms).