This question already has answers here:
Is main() really start of a C++ program?
(12 answers)
Closed 9 years ago.
i have a question for you.
I need find out if i can use some function before or after main() function ended. I can't find some examples for C language.
Can you give me some advice or examples. Thanks a lot.
If you are using GCC, you can create construtors/destructor functions:
The constructor attribute causes the function to be called automatically before execution enters main(). Similarly, the destructor attribute causes the function to be called automatically after main() completes or exit() is called. Functions with these attributes are useful for initializing data that is used implicitly during the execution of the program.
Sample:
void __attribute__ ((constructor)) ctor() { printf("1"); }
void __attribute__ ((destructor)) dtor() { printf("3"); }
int main() { printf("2"); }
Output:
123
There is atexit function in C (std::atexit in C++) which registers a function to be called at program termination.
You could use atexit() for normal program exit, a signal handler (in UNIX) for abnormal exit.
GCC also has the constructor and destructor function attributes that do what you want, that's not vanilla C or C++ though.
There are many solutions to this problem, some of which have been provided:
Static CRT intitialization/termination (static object destructor
"hook")
Renaming your main and wrapping it with the real main
Registering a hook with atexit()
It's not clear what you're trying to do, or even whether the question intends "can I do it" or "is it safe to do it"? Can you clarify?
Related
This question already has answers here:
Is main() really start of a C++ program?
(12 answers)
Closed 4 years ago.
Why main() function run first of all then other functions what if we want another function run first then main function in c or c++.
Can anyone explain logic behind it.thanks.
Because that's what the Standard defines the language to use (C++ quoted here):
[basic.start.main]
A program shall contain a global function called main. Executing a program starts a main thread of execution (...) in which the main function is invoked (...)
So the compiler has to produce the binary in a way that calls main when the program is started by the operating system, or, in case of freestanding environments, when it's loaded.
Technically speaking, it doesn't have to be the first call in the resulting assembly. The compiler can insert some additional startup code (like initializing variables etc.), which can itself be grouped into functions. This is out of concern of a C++ program developer, but becomes quite important on embedded systems, where you need/want to be aware of almost every instruction executed.
A program has to start somewhere... As far as the developer is concerned that's typically main() - referred to as the "entry point".
If you want to do certain things at the beginning of your program, then just move the content of your main() into another function (like run()), and place the startup code in main() before calling run().
#include <stdio.h>
void init(void) {
/* startup */
}
void run(void) {
/* application functionality */
}
int main(void) {
init();
run();
exit 0;
}
As far as the wider system is concerned there is an amount of setup that happens first:
The process needs to be created (e.g: fork())
The stack needs to be prepared
Global variables need to be initialized
etc...
This is because you can create any number of functions in a program. You can have 1 function, 10, 2340 functions, or whatever. The program needs to know where to start. This is the purpose of the main function, as that is always the first function called.
You need to have a place in the program where the execution starts. In C it is function main.
But the program starts executing before the call to the main. That before main code prepares the execution environment for your program and it is called
a startup code.
I've compiled LuaJIT with MSVC x64, which means that there should be full C++ exception interoperability, according to the official LuaJIT website.
One of the points states that "Throwing Lua errors across C++ frames is safe. C++ destructors will be called."
I assumed that this means I can use lua_error in a C++ function and not worry about objects on the stack:
struct Test
{
Test() {std::cout<<"Constructor"<<std::endl;}
~Test() {std::cout<<"Destructor"<<std::endl;}
};
int some_function(lua_State *l)
{
Test t {};
lua_pushstring(l,"error message");
lua_error(l);
return 0;
}
(The function is called from within a Lua-script)
However, the destructor is never called. So what does that point on the website actually mean? How can I use lua_error without having to worry about memory leaks?
According to this question, the problem can be solved by compiling Lua as C++-code, but since I'm using LuaJIT, I'm not sure if that won't cause me any problems?
As a newbie to c++, coming from python, I'm not sure why c++ doesn't allow statements outside of a function (in the global namespace?). It seems like this could be useful to do some initialization before main() is called or other functions are even declared. (I'm not trying to argue with the compiler, I'd just like to know the thought process behind implementing it this way.)
When you're running a python program, the interpreter runs through it from top to bottom executing as it goes. In C++, that doesn't happen. The compiler builds all your functions into little blobs of machine code and then the linker hooks them up. At runtime, the operating system calls your main function, and everything goes on from there. In that context, code outside of functions is meaningless - when would it run?
This can be thought of as a style difference between C++ and Python. However, there are pretty good reasons for it too. In C and C++, there is a very clear and specific place that the execution of your code starts from, and that's the beginning of the main() function (of course, this is only an approximation of the truth, but we can ignore that for now.) Actually, a C/C++ program starts and ends with the main() function which - in my opinion - helps quite a lot when you want to understand what a program actually does. The high-level flow of the program is clearer. Contrast this with the alternative; with code scattered all through the file and in between functions and whatnot.
Even in a well-organized and non-trivial Python program, you put your main body of code under an if __name__ == "__main__":, don't you?
Now for some stuff that are a little bit more advanced. There are ways for code to run before the main() function is called. Here's one of them:
#include <iostream>
using namespace std;
bool RunBeforeMain ()
{
cout << "Before main()!" << endl;
return true;
}
// This variable here causes the above function to be called
bool ignore_this_variable = RunBeforeMain ();
int main ()
{
cout << "Start of main()" << endl;
return 0;
}
Also, the constructors of all the global variables and all the static members of classes and some platform-dependent stuff are run before main(). Analogously, there are ways for code to run after the main() is finished. Those are usually the destructors for objects constructed before main() began, and functions registered with the atexit() function.
The main() is the access point to the program. So any code you wanna write would be needs to have an order of execution from that point.
Static variables are initiated before the main() is executed, so you can initiate whatever variables you need before that.
But if you want run code that initiates the state of the program, you should do it just in the beginning of the program, and abuse the static variables and do it some constructor.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Does the program execution always start from main in C?
i want to start the execution of my program which contains 2 functions (excluding main)
void check(void)
void execute(void)
i want to start my execution from check(), is it possible in c/c++?
You can do this with a simple wrapper:
int main()
{
check();
}
You can't portably do it in any other way since the standard explicitly specifies main as the program entry point.
EDIT for comment: Don't ever do this. In C++ you could abuse static initialization to have check called before main during static init, but you still can't call main legally from check. You can just have check run first. As noted in a comment this doesn't work in C because it requires constant initializers.
// At file scope.
bool abuse_the_language = (check(), true);
int main()
{
// No op if desired.
}
Various linkers have various options to specify the entry point. Eg. Microsoft linker uses /ENTRY:function:
The /ENTRY option specifies an entry point function as the starting
address for an .exe file or DLL.
GNU's ld uses the -e or ENTRY() in the command file.
Needles to say, modifying the entry point is a very advanced feature which you must absolutely understand how it works. For one, it may cause skipping the loading the standard libraries initialization.
int main()
{
check();
return 0;
}
Calling check from main seems like the most logical solution, but you could still explore using /ENTRY to define another entry point for your application. See here for more info.
You cannot start in something other than main, although there are ways to have some code execute before main.
Putting code in a static initialization block will have the code run prior to main; however, it won't be 100% controllable. while you can be assured it runs prior to main, you cannot specify the order that two static initialization blocks will run prior to them both executing before main.
Linkers and loaders both have the concept of main held as a shared "understood" start of a C / C++ program; however, there is code that runs prior to main. This code is responsible for "setting up the environment" of the program (things like setting up stdin or cin). By putting code in a static initialization block, you effectively say, "hey you need to do this too to have the right environment". Generally, this should be something small, that can stand independently in execution order of other items.
If you need two or three things to execute in order before main, then make them into proper functions and call them at the beginning of main.
There is a contrived way to achieve that, but it is nothing more than a hack.
The idea is to create a static library containing the main function, and make it call your "check" function.
The linker will resolve the symbol when linking against your "program", and your "program" code will indeed not have a main by itself.
This is NOT recommended, unless you have very specific needs (an example that pops to mind is Windows Screensavers, as the helper library that comes with the Windows SDK has a main function that performs specific initialization like parsing the command line).
It may be supportted by the compiler. For example, gcc, you can use -nostartfiles and --entry=xxx to set the entry point of the program. The default entry point is _start, which will call the function main.
You can "intercept" the call to main by creating an object before the main starts. The constructor needs to execute your function.
#include <iostream>
void foo()
{
// do stuff
std::cout<<"exiting from foo" <<std::endl;
}
struct A
{
A(){ foo(); };
};
static A a;
int main()
{
// something
std::cout<<"starting main()" <<std::endl;
}
I have found solution to my own question.
we can simply use
#pragma startup function-name <priority>
#pragma exit function-name <priority>
These two pragmas allow the program to specify function(s) that should be called either upon program startup (before the main function is called), or program exit (just before the program terminates through _exit).
The specified function-name must be a previously declared function taking no arguments and returning void; in other words, it should be declared as:
void func(void);
The optional priority parameter should be an integer in the range 64 to 255. The highest priority is 0. Functions with higher priorities are called first at startup and last at exit. If you don't specify a priority, it defaults to 100.
thanks!
Can I write a program in C or in C++ with two main functions?
No. All programs have a single main(), that's how the compiler and linker generate an executable that start somewhere sensible.
You basically have two options:
Have the main() interpret some command line arguments to decide what actual main to call. The drawback is that you are going to have an executable with both programs.
Create a library out of the shared code and compile each main file against that library. You'll end up with two executables.
You can have two functions called main. The name is not special in any way and it's not reserved. What's special is the function, and it happens to have that name. The function is global. So if you write a main function in some other namespace, you will have a second main function.
namespace kuppusamy {
int main() { return 0; }
}
int main() { kuppusamy::main(); }
The first main function is not special - notice how you have to return explicitly.
Yes; however, it's platform specific instead of standard C, and if you ask about what you really want to achieve (instead of this attempted solution to that problem), then you'll likely receive answers which are more helpful for you.
No, a program can have just 1 entry point(which is main()). In fact, more generally, you can only have one function of a given name in C.
If one is static and resides in a different source file I don't see any problem.
No, main() defines the entry point to your program and you must only one main() function(entry point) in your program.
Frankly speaking your question doesn't make much sense to me.
What do you mean by "main function"? If you mean the first function to execute when the program starts, then you can have only one. (You can only have one first!)
If you want to have your application do different things on start up, you can write a main function which reads the command line (for example) and then decides which other function to call.
In some very special architecture, you can. This is the case of the Cell Processor where you have a main program for the main processor (64-bit PowerPC Processors Element called PPE) and one or many main program for the 8 different co-processor (32-bit Synergistic Processing Element called SPE).
No, you cannot have more than one main() function in C language. In standard C language, the main() function is a special function that is defined as the entry point of the program. There cannot be more than one copy of ANY function you create in C language, or in any other language for that matter - unless you specify different signatures. But in case of main(), i think you got no choice ;)
No,The main() is the entry point to your program,since u can't have two entry points you cant have two main().
You can write it, and it'll compile, but it won't link (unless your linker is non-comformant)
The idiom is to dispatch on the value of argv[0]. With hardlinks (POSIX) you don't even lose diskspace.
Standard C doesn’t allow nested functions but GCC allows them.
void main()
{
void main()
{
printf(“stackoverflow”);
}
printf(“hii”);
}
The o/p for this code will be -hii
if you use GCC compiler.
There is a simple trick if you want to use 2 main() in your program such that both are successfully executed;you can use define.Example-
void main()
{
printf("In 1st main\n");
func1();
}
#define main func1
void main()
{
printf("In 2nd main\n");
}
Here the o/p will be:
In 1st main
In 2nd main
NOTE:here warning conflicting types of func1 will be generated.
And yes don’t change the place of define.