I have come a cross different ways of writing a functions e.g. consider main function in following ways
int main()
{
some thing here;
return 0;
}
Second and third variant could be like
void main()
{
some thing here;
}
int main(int argv , char *argc[])
{
some thing here;
return 0;
}
So how can someone possibly write a single function in different ways? Which could cause errors in my opinion ?
How to write such functions ? Is is similar to overloading overloading or overwriting concept in java ?
Is there a facility to use a single name for many functions ?
Please provide an example of using such functions ?
I am trying to answer your questions here:
First, main is of course a function. In fact, main is the entry point for every c program, and every c program must have a main function.
A C-Program consists of variables and functions, and MUST have at least one function. In the minimal case, this will be the main function.
Ok, so much for the theory and the first part of your question.
What i think is the thing thats bugging your mind is: You think that main() is a C library function and therefore it cannot be "overloaded".
The truth is, its not a library function, its just a specific entry point for your program, and it identifies itself by the name "main", not the return type or arguments it takes.
You can write a C program with just
main(){
[your code here]
}
or also
int main(int argc, char * argv[]){
[your code here]
}
So you declare and define the main function yourself and you do it the way it best fits your program's need (i.e. if your program takes command line variables, you will pick the second example).
Remember, main is not a library function, its just a naming convention where a C-program starts.
You can also have a look at The C Programming Language (Second Edition) by Brian Kernighan and Dennis Ritchie, pages 5-7.
Related
I often see programs where people put argc and argv in main, but never make any use of these parameters.
int main(int argc, char *argv[]) {
// never touches any of the parameters
}
Should I do so too? What is the reason for that?
The arguments to the main function can be omitted if you do not need to use them. You can define main this way:
int main(void) {
// never touches any of the parameters
}
Or simply:
int main() {
// never touches any of the parameters
}
Regarding why some programmers do that, it could be to conform to local style guides, because they are used to it, or simply a side effect of their IDE's source template system.
When you have a function, it's obviously important that the arguments passed by the caller always match up properly with the arguments expected by the function.
When you define and call one of your own functions, you can pick whatever arguments make sense to you for the function to accept, and then it's your job to call your function with the arguments you've decided on.
When you call a function that somebody else defined — like a standard library function — somebody else picked the arguments that function would accept, and it's your job to pass them correctly. For example, if you call the standard library function strcpy, you just have to pass it a destination string, and a source string, in that order. If you think it would make sense to pass three arguments, like the destination string, and the size of the destination string, and the source string, it won't work. You don't get to make up the way you'll call the function, because it's already defined.
And then there are a few cases where somebody else is going to call a function that you defined, and the way they're going to call it is fixed, such that you don't have any choice in the way you define it. The best example of this (except it turns out it's not such a good example after all, as we'll see) is main(). It's your job to define this function. It's not a standard library function that somebody else is going to define. But, it is a function that somebody else — namely, the C start-up code — is going to call. That code was written a while ago, by somebody else, and you have no control over it. It's going to call your main function in a certain way. So you're constrained to write your main function in a way that's compatible with the way it's going to be called. You can put whatever you want in the body of your main function, but you don't get to pick your own arguments: there are supposed to be two of those, an int and a char **, in that order.
Now, it also turns out that there's a very special exception for main. Even though the caller is going to be calling it with those two predefined arguments, if you're not interested in them, and if you define main with no arguments, instead, like this:
int main()
{
/* ... */
}
your C implementation is required to set things up so that nothing will go wrong, no problems will be caused by the caller passing those two arguments that your main function doesn't accept.
So, in answer to your question, many programs are written to accept int argc and char **argv because they're complying with the simple rule: those are the arguments the caller is accepting, so those are the arguments they believe their main function should be defined as accepting, even if it doesn't actually use them.
Programmers who define main functions that accept argc and argv without using them either haven't heard of, or choose not to make use of, the special exception that says they don't have to. Personally, I don't blame them: that special exception for main is a strange one, which didn't always exist, so since it's not wrong to define main as taking two required arguments but not using them, that could be considered "better style".
(Yes, if you define a function that fails to actually use the arguments it defines, your compiler might warn you about this, but that's a separate question.)
How to #define a function to be replaced by another?
For example, if I have a function Stuff(int numbers) and would like to replace it with Stuff2(int numbers, int otherNumbers).
So, when Stuff() is called, Stuff2() is used instead.
Using #define is a basic global text replacement.
#define Stuff(number) Stuff2(number,0)
The zero is here for illustration; replace it with whatever the appropriate default is. If necessary, you could even call a function or use more macro magic to compute it.
Update
So, following the commentary, OP is trying to redirect main().
This is a technique with a highly-specific use-case. The first thing to remember is that main() is not a normal function. That’s right, main() is special.
As a result, you cannot just replace main() and expect things to work happily. There must be a main(), and it must be declared according to one of your compiler’s accepted variations. (IMO, you should prefer to use one of the two variations required by the C Standard.)
Intercepting the user’s main()
The technique is commonly used by libraries that want to have an app-level control over your application, but want you to think that everything is normal.
They do this by declaring main() in the library’s code, and #defining main to something else in the header so that when you write "main()" it is actually a different function. For example:
// quuxlib.c
int main( int argc, char** argv )
{
int exit_code = 0;
// library does initializations here
...
// call the user's main(), LOL
exit_code = UsersMain( argc, argv );
// perform cleanup
...
return exit_code;
}
The library's header:
// quuxlib.h
#define main UsersMain
...
And now the user’s code looks normal:
#include "quuxlib.h"
int main( int argc, char** argv ) // This is actually UsersMain()!
{
// Use quuxlib without any further thought
}
Caveats and Best Practices
This technique is, IMHO, bad design. It seeks to obscure what is actually happening. A better library design would be explicit, and either:
Require you to properly initialize and finalize the library in your main()
Expect you to use an explicit entry procedure
The former is preferred, as it gets along with all kinds of stuff better. For example, Tcl hooks things properly. Here you simply create an interpreter, use it, and terminate normally.
#include "tcl.h"
int main()
{
Tcl_Interp* interp = Tcl_CreateInterp();
int status = Tcl_Eval( interp, "puts {Hello world!}" );
return 0;
}
Tcl also goes one step further, providing Tcl_Main and Tcl_AppInit to make life very easy. See an example here.
Using an explicit entry procedure is the very same thing as the main() replacement trick, just without pretending anything:
#include "quuxlib.h"
int AppMain() // required by QuuxLib
{
// my main program here
...
return 0;
}
The problems
To finish, the problems with re#defining main are:
it obscures what is really happening
it uses a global macro replacement
Good design doesn't try to hide things from you. A global macro replacement is also bad. In this case, "main" is not a reserved word. You could have a valid local identifier called "main". Using a global macro replacement obviates that possibility.
Finally, having a library provide explicit initialization and finalization procedures rather than take over main increases the flexibility available to the user. A library that takes your main() cannot be used with another library that does the same, nor can it really be trusted to handle things that can go wrong (IMHO) as well as a library the provides proper and explicit hooks for the library user to handle that kind of stuff.
The trade-off is pretty for common cases vs versatility.
Well, I think I’m pretty firmly into rambling now, so it’s time to stop...
I've seen lots of different ways this can be done, none of them seem ideal in terms of having to use lots of wrappers and callbacks. Is there a simple way of doing this?
For example, we have this:
//foo.go
package foo
import "C"
//export SayFive
func SayFive() int {
return 5
}
This has been stripped down to the minimum now, and all I want to be able to do at this point is call that SayFive function in C.
However, not at the top of this file. It's very simple and useful to be able to do that, but I'm looking for a way like this:
//foo.c
#include <stdio.h>
int main() {
int a = SayFive();
}
I've seen in examples that are like the above, that #include "_cgo_export.h" which makes total sense, but when I've done that and tried to compile it, it fails.
Could anyone explain the whole process involved that would allow us to do this?
You can call C from Go and Go from C, but only within the framework of a Go program.
So your example of a C program with a main() won't work, because that would be calling Go from within the framework of a C program.
In other words, Go can't make objects you can link statically or dynamically with C programs.
So you'll have to turn what you want to do on its head and make the Go program the master, and call the C program parts from it. That means the program with the main() function must be a Go program.
Hope that makes sense!
I went through all sorts of quine problems, but my task was to get a quine problem without main(), and loops are also forbidden.
Without loop, it is easy, but I can't figure out how to write one without main(). Can anyone help me or provide me with a link?
You cannot create a (non-freestanding) C program without a main() function. Thus, creating a quine in C without a main() is impossible in the usual sense.
That said, depending on how you define a quine, you might be able to construct a source file which fails to compile, but for which the compile error (on a certain specific compiler) is the contents of the source file.
First thing its impossible to write program without main function because compiler always starts execution from main() function, without main function linker will not be aware of start of data segment.
Yeah but playing with some tricks with preprocessor you can do it, but this is not a good method to do that.
http://www.gohacking.com/2008/03/c-program-without-main-function.html
This might help you.
Take a look here too:
Is a main() required for a C program?
#include <stdio.h>
int
foo(void) {
printf("pong!\n");
return 0;
}
int main() __attribute__((weak, alias("foo")));
There is main() declaration, but not definition.
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
main() in C, C++, Java, C#
I'm new to programming in general, and C in particular. Every example I've looked at has a "main" function - is this pre-defined in some way, such that the name takes on a special meaning to the compiler or runtime... or is it merely a common idiom among C programmers (like using "foo" and "bar" for arbitrary variable names).
No, you need to define main in your program. Since it's called from the run-time, however, the interface your main must provide is pre-defined (must return an int, must take either zero arguments or two, the first an int, and the second a char ** or, equivalently, char *[]). The C and C++ standards do specify that a function with external linkage named main acts as the entry point for a program1.
At least as the term is normally used, a predefined function would be one such as sin or printf that's in the standard library so you can use it without having to write it yourself.
1If you want to get technical, that's only true for a "hosted" implementation -- i.e., the kind most of us use most of the time that produces programs that run on an operating system. A "free-standing" implementation (one produces program that run directly on the "bare metal" with no operating system under it) is free to define the entry point(s) as it sees fit. A free-standing implementation can also leave out most of the normal run-time library, providing only a handful of headers (e.g., <stddef.h>) and virtually no standard library functions.
Yes, main is a predefined function in the general sense of the the word "defined". In other words, the C language standard specifies that the function called at program startup shall be named main. It is not merely a convention used by programmers as we have with foo or bar.
The fine print: from the perspective of the technical meaning of the word "defined" in the context of C programming, no the main function is not "predefined" -- the compiler or C library do not supply a predefined function named main. You need to define your own implementation of the main function (and, obviously, you should name it main).
There is typically a piece of code that normal C programs are linked to which does:
extern int main(int argc, char * argv[], char * envp[]);
FILE * stdin;
FILE * stdout;
FILE * stderr;
/* ** setup argv ** */
...
/* ** setup envp ** */
...
/* ** setup stdio ** */
stdin = fdopen(0, "r");
stdout = fdopen(1, "w");
stderr = fdopen(2, "w");
int rc;
rc = main(argc, argv, envp); // envp may not be present here with some systems
exit(rc);
Note that this code is C, not C++, so it expects main to be a C function.
Also note that my code does no error checking and leaves out a lot of other system dependent stuff that probably happens. It also ignores some things that happen with C++, objective C, and various other languages that may be linked to it (notably constructor and destructor calling, and possibly having main be within a C++ try/catch block).
Anyway, this code knows that main is a function and takes arguments. If your main looks like:
int main(void) {
Then it still gets passed arguments, but they are ignored.
This code specially linked so that it is called when the program starts up.
You are completely free to write your own version of this code on many architectures, but it relies on intimate knowledge of how the operating system starts a new program as well as the C (and C++ and possibly Objective C) run time. It is likely to require some assembly programming and or use of compiler extensions to properly build.
The C compiler driver (the command you usually call when you call the compiler) passes the object file containing all of this (often called crt0.0, for C Run Time ...) along with the rest of your program to the linker, unless told not to.
When building an operating system kernel or an embedded program you often do not want to use the standard crt*.o file. You also may not want to use it if you are building a normal application in another programming language, or have some other non-standard requirements.
No, or you couldn't define one.
It's not predefined, but its meaning as an entry point, if it is present, is defined.