When a C/C++ program is called like:
./prog --arg=42
the command line arguments are forwarded to the main function
int main (int argc, char* argv[])
where the arguments can be parsed (or forwarded to some library which does the parsing).
I wonder if it is possible to intercept the arguments before the main function is called by the C runtime.
Since I write a replacement library I cannot use an init function like like my_lib::init(argc, argv).
I am aware of the __attribute__((constructor)) for a function so it is called before main is invoked, however I don't know how to get the command line arguments in such a tagged function.
I think there is no standard ways to intercept calling the executable's entry point main().
However, you could adjust the linking process of your executable, possibly using the --wrap and -u options of ld, for example. There are further options to replace symbols in the linking process, consider your linker's manual.
I know there are two different signatures to write the main method -
int main()
{
//Code
}
or for handling command line argument, we write it as-
int main(int argc, char * argv[])
{
//code
}
In C++ I know we can overload a method, but in C how does the compiler handle these two different signatures of main function?
Some of the features of the C language started out as hacks which just happened to work.
Multiple signatures for main, as well as variable-length argument lists, is one of those features.
Programmers noticed that they can pass extra arguments to a function, and nothing bad happens with their given compiler.
This is the case if the calling conventions are such that:
The calling function cleans up the arguments.
The leftmost arguments are closer to the top of the stack, or to the base of the stack frame, so that spurious arguments do not invalidate the addressing.
One set of calling conventions which obeys these rules is stack-based parameter passing whereby the caller pops the arguments, and they are pushed right to left:
;; pseudo-assembly-language
;; main(argc, argv, envp); call
push envp ;; rightmost argument
push argv ;;
push argc ;; leftmost argument ends up on top of stack
call main
pop ;; caller cleans up
pop
pop
In compilers where this type of calling convention is the case, nothing special need to be done to support the two kinds of main, or even additional kinds. main can be a function of no arguments, in which case it is oblivious to the items that were pushed onto the stack. If it's a function of two arguments, then it finds argc and argv as the two topmost stack items. If it's a platform-specific three-argument variant with an environment pointer (a common extension), that will work too: it will find that third argument as the third element from the top of the stack.
And so a fixed call works for all cases, allowing a single, fixed start-up module to be linked to the program. That module could be written in C, as a function resembling this:
/* I'm adding envp to show that even a popular platform-specific variant
can be handled. */
extern int main(int argc, char **argv, char **envp);
void __start(void)
{
/* This is the real startup function for the executable.
It performs a bunch of library initialization. */
/* ... */
/* And then: */
exit(main(argc_from_somewhere, argv_from_somewhere, envp_from_somewhere));
}
In other words, this start module just calls a three-argument main, always. If main takes no arguments, or only int, char **, it happens to work fine, as well as if it takes no arguments, due to the calling conventions.
If you were to do this kind of thing in your program, it would be nonportable and considered undefined behavior by ISO C: declaring and calling a function in one manner, and defining it in another. But a compiler's startup trick does not have to be portable; it is not guided by the rules for portable programs.
But suppose that the calling conventions are such that it cannot work this way. In that case, the compiler has to treat main specially. When it notices that it's compiling the main function, it can generate code which is compatible with, say, a three argument call.
That is to say, you write this:
int main(void)
{
/* ... */
}
But when the compiler sees it, it essentially performs a code transformation so that the function which it compiles looks more like this:
int main(int __argc_ignore, char **__argv_ignore, char **__envp_ignore)
{
/* ... */
}
except that the names __argc_ignore don't literally exist. No such names are introduced into your scope, and there won't be any warning about unused arguments.
The code transformation causes the compiler to emit code with the correct linkage which knows that it has to clean up three arguments.
Another implementation strategy is for the compiler or perhaps linker to custom-generate the __start function (or whatever it is called), or at least select one from several pre-compiled alternatives. Information could be stored in the object file about which of the supported forms of main is being used. The linker can look at this info, and select the correct version of the start-up module which contains a call to main which is compatible with the program's definition. C implementations usually have only a small number of supported forms of main so this approach is feasible.
Compilers for the C99 language always have to treat main specially, to some extent, to support the hack that if the function terminates without a return statement, the behavior is as if return 0 were executed. This, again, can be treated by a code transformation. The compiler notices that a function called main is being compiled. Then it checks whether the end of the body is potentially reachable. If so, it inserts a return 0;
There is NO overloading of main even in C++. Main function is the entry point for a program and only a single definition should exist.
For Standard C
For a hosted environment (that's the normal one), the C99 standard
says:
5.1.2.2.1 Program startup
The function called at program startup is named main. The implementation declares no prototype for this function. It shall be
defined with a return type of int and with no parameters:
int main(void) { /* ... */ }
or with two parameters (referred to here as argc and argv, though any names may be used, as they are local to the function in which they
are declared):
int main(int argc, char *argv[]) { /* ... */ }
or equivalent;9) or in some other implementation-defined manner.
9) Thus, int can be replaced by a typedef name defined as int, or the type of argv can be written as char **argv, and
so on.
For standard C++:
3.6.1 Main function [basic.start.main]
1 A program shall contain a global function called main, which is the designated start of the program. [...]
2 An implementation shall not predefine the main function. This function shall not be overloaded. It shall
have a return type of type int, but otherwise its type is implementation defined.
All implementations
shall allow both of the following definitions of main:
int main() { /* ... */ }
and
int main(int argc, char* argv[]) { /* ... */ }
The C++ standard explicitly says "It [the main function] shall have a return type of type int, but otherwise its type is implementation defined", and requires the same two signatures as the C standard.
In a hosted environment (A C environment which also supports the C libraries) - the Operating System calls main.
In a non-hosted environment (One intended for embedded applications) you can always change the entry point (or exit) of your program using the pre-processor directives like
#pragma startup [priority]
#pragma exit [priority]
Where priority is an optional integral number.
Pragma startup executes the function before the main (priority-wise) and pragma exit executes the function after the main function. If there is more than one startup directive then priority decides which will execute first.
There is no need for overloading. Yes, there are 2 versions, but only one can be used at the time.
This is one of the strange asymmetries and special rules of the C and C++ language.
In my opinion it exists only for historical reasons and there's no real serious logic behind it. Note that main is special also for other reasons (for example main in C++ cannot be recursive and you cannot take its address and in C99/C++ you are allowed to omit a final return statement).
Note also that even in C++ it's not an overload... either a program has the first form or it has the second form; it cannot have both.
What's unusual about main isn't that it can be defined in more than one way, it's that it can only be defined in one of two different ways.
main is a user-defined function; the implementation doesn't declare a prototype for it.
The same thing is true for foo or bar, but you can define functions with those names any way you like.
The difference is that main is invoked by the implementation (the runtime environment), not just by your own code. The implementation isn't limited to ordinary C function call semantics, so it can (and must) deal with a few variations -- but it's not required to handle infinitely many possibilities. The int main(int argc, char *argv[]) form allows for command-line arguments, and int main(void) in C or int main() in C++ is just a convenience for simple programs that don't need to process command-line arguments.
As for how the compiler handles this, it depends on the implementation. Most systems probably have calling conventions that make the two forms effectively compatible, and any arguments passed to a main defined with no parameters are quietly ignored. If not, it wouldn't be difficult for a compiler or linker to treat main specially. If you're curious how it works on your system, you might look at some assembly listings.
And like many things in C and C++, the details are largely a result of history and arbitrary decisions made by the designers of the languages and their predecessors.
Note that both C and C++ both permit other implementation-defined definitions for main -- but there's rarely any good reason to use them. And for freestanding implementations (such as embedded systems with no OS), the program entry point is implementation-defined, and isn't necessarily even called main.
The main is just a name for a starting address decided by the linker where main is the default name. All function names in a program are starting addresses where the function starts.
The function arguments are pushed/popped on/from the stack so if there are no arguments specified for the function there are no arguments pushed/popped on/off the stack. That is how main can work both with or without arguments.
Well, the two different signatures of the same function main() comes in picture only when you want them so, I mean if your programm needs data before any actual processing of your code you may pass them via use of -
int main(int argc, char * argv[])
{
//code
}
where the variable argc stores the count of data that is passed and argv is an array of pointers to char which points to the passed values from console.
Otherwise it's always good to go with
int main()
{
//Code
}
However in any case there can be one and only one main() in a programm, as because that's the only point where from a program starts its execution and hence it can not be more than one.
(hope its worthy)
A similar question was asked before: Why does a function with no parameters (compared to the actual function definition) compile?
One of the top-ranked answers was:
In C func() means that you can pass any number of arguments. If you
want no arguments then you have to declare as func(void)
So, I guess it's how main is declared (if you can apply the term "declared" to main). In fact you can write something like this:
int main(int only_one_argument) {
// code
}
and it will still compile and run.
You do not need to override this.because only one will used at a time.yes there are 2 different version of main function
If I want to keep the bulk of my code for processing command line arguments out of main (for organization and more readable code), what would be the best way to do it?
void main(int argc, char* argv[]){
//lots of code here I would like to move elsewhere
}
Either pass them as parameters, or store them in global variables. As long as you don't return from main and try to process them in an atexit handler or the destructor of an object at global scope, they still exist and will be fine to access from any scope.
For example:
// Passing them as args:
void process_command_line(int argc, char **argv)
{
// Use argc and argv
...
}
int main(int argc, char **argv)
{
process_command_line(argc, argv);
...
}
Alternatively:
// Global variables
int g_argc;
char **g_argv;
void process_command_line()
{
// Use g_argc and g_argv
...
}
int main(int argc, char **argv)
{
g_argc = argc;
g_argv = argv;
process_command_line();
...
}
Passing them as parameters is a better design, since it's encapsulated and let's you modify/substitute parameters if you want or easily convert your program into a library. Global variables are easier, since if you have many different functions which access the args for whatever reason, you can just store them once and don't need to keep passing them around between all of the different functions.
One should keep to standards wherever practical. Thus, don't write
void main
which has never been valid C or C++, but instead write
int main
With that, your code can compile with e.g. g++ (with usual compiler options).
Given the void main I suspect a Windows environment. And anyway, in order to support use of your program in a Windows environment, you should not use the main arguments in Windows. They work in *nix because they were designed in and for that environment; they don't in general work in Windows, because by default (by very strong convention) they're encoded as Windows ANSI, which means they cannot encode filenames with characters outside the user's current locale.
So for Windows you better use the GetCommandLine API function and its sister parsing function. For portability this should better be encapsulated in some command line arguments module. Then you need to deal with the interesting problem of using wchar_t in Windows and char in *nix…
Anyway, I'm not sure of corresponding *nix API, or even if there is one, but google it. In the worst case, for *nix you can always initialize a command line arguments module from main. The ugliness for *nix stems directly from the need to support portability with C++'s most non-portable, OS-specific construct, namely standard main.
Simply pass argc and argv as arguments of the function in which you want to process them.
void parse_arg(int argc, char *argv[]);
Linux provides program_invocation_name and program_invocation_name_short.
Check out the "getoptlong" family of functions and libraries. These offer a structured way of defining the arguments your program expects and can then parse them readily for you. Can also help with the generation of documentation / help responses.
It's an old library in the UNIX world, and there is a .Net implementation in C# too. (+ Perl, Ruby, & probably more. Nice to have a single paradigm usable across all of these! Learn once, use everywhere!)
When I run a Java Program on Eclipse, each time I run a file, Compiler will check does it has main, if it has, I can run. And if not, I cannot.
But when I run a C++ Program (CDT) on Eclipse using MinGW, at Compiler doesn't work like that. After I compile, don't matter I run from which file, Compiler will search whole project to find ONE MAIN So, if I has many main file, I will receive error.
Please tell me in Eclipse, how to treat C++ Compiler to have multi main file and work like on Java: it just find main on which file I run from.
#: I have multi main file just for debugging purpose. !!!
Thanks :)
unlike java in a C/C++ you can only have one main:
The main() function is special; normally every C and C++ program must
define it exactly once.
( source )
But: As a workaround you can use preprocessor to decide which of your main's you want to use.
Example:
#ifdef FIRST_MAIN
int main(int argc, char** argv)
{
printf("first");
return (EXIT_SUCCESS);
}
#elif SECOND_MAIN
int main(int argc, char** argv)
{
printf("second");
return (EXIT_SUCCESS);
}
#else
int main(int argc, char** argv)
{
printf("default");
return (EXIT_SUCCESS);
}
#endif
Now you can decide wich one you want to use by setting proper flag at compiletime. If none is set you'll use the default one (#else part).
Alternative: Exclude all your files containing a main-function from compilation and include only the one you need. However, this will only work if those files dont contain more than the main.
I am writing my first LLVM sample. I am trying to build a small LLVM module consisting of a function which takes in a name of a function and returns a pointer to it. The problem is I don't know how to generate function pointers in LLVM. I have got a Function object by calling getDeclaration(...). Is there some way I can get a pointer to it?
Function is a GlobalValue, so it is the pointer by itself. In the meantime, you can use LLVM's C++ backend to generate the C++ API calls which will recreate the IR you're feeding to llc.
For example, feed the following code into http://llvm.org/demo:
void foo(int (*bar)(int));
int factorial(int X);
int main(int argc, char **argv) {
foo(factorial);
}
Make sure you have the "Show LLVM C++ API code" checkbox selected and you'll see the corresponding LLVM IR and the C++ API calls which will recreate it.