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!)
Related
I have to modify previously written C++ code and for program takes some command line arguments.
Other people will be doing review and will be testing this code, to ease them, I have written this...
int main (int argc, char *argv[])
{
// To do testing just uncomment the below line.
#define TESTING
#ifdef TESTING
argc = ARGUMENT_COUNT;
argv[1] = new char[strlen(INPUT_FILE) + 1 ];
strcpy(argv[1], INPUT_FILE);
argv[2] = new char[strlen(MERGE_FILE) + 1 ];
strcpy(argv[2], MERGE_FILE);
.
.
.
#endif
My question: is there any other better way to handle this type of testing where command line is involved and the same variable argv is used everywhere.
Note: I dont have IDE support. I am using vi editor on a remote server.
Put the code that processes the command line arguments into a separate function, maybe even in a method in a class that stores the values and provides them to your application.
Then, call this function/method from your main() function. Finally, implement test program(s) with test cases/functions which also call the function with the prepared test data and check for the expected result.
This way, production implementation and tests are clearly separated, no need to use a hack to provide the test data etc.
If your argv can be const, you can create a new argv and replace the origin one like this.
int main (int argc, const char *argv[])
{
// To do testing just uncomment the below line.
#define TESTING
#ifdef TESTING
const char* args[]={
"arg 1","arg 2","arg 3",nullptr
};
argc = sizeof(args)/sizeof(char*);
argv = args;
#endif
}
If it's for test propose, use test framework is better choice.
The C++ standard does allow you to change argc and argv. Don't forget to release the memory you've allocate with new[] though.
But a better alternative would be to pass the arguments via your IDE or via a start-up script, rather than hack the code in this way.
Note that the behaviour of calling main from itself (even indirectly; i.e. via another function) is undefined in C++. So don't create a solution that does that.
For testing, I use the suite available in Boost. See www.boost.org.
First, I would use a testing framework, but if I were to roll my own testing I would probably abstract command line arguments. Create a class that parses and holds the arguments. Use dependency injection to send either argv or your testing data to the constructor.
Is there any fundamental reason why the new C++17 (or later) won't allow for an alternative way of writing main as
int main(std::vector<std::string> args){...}
? I know that one needs compatibility with previous code, so
int main(int, char**)
still has to exist, but is there anything technical that prevents the first "alternative" declaration?
Here's how to do that yourself, trivially, in a very few lines of code:
auto my_main( std::vector<std::string> const& args ) -> int;
auto main( int n_args, char** args )
-> int
{ return my_main( std::vector<std::string>( args, args + n_args ) ); }
Modulo notation I believe this approch is presented in the Accelerated C++ book, i.e. it's well known.
One doesn't need to add this to the standard: those who find it useful can just copy and paste the code.
Others may not find it useful: it doesn't work so well in Windows, because by common convention the main arguments are not Unicode in Windows, and Microsoft's setlocale explicitly does not support UTF-8 locales.
This might be somewhat non-trivial to implement, at least in one respect.
This basically requires kind of a reverse-lookup form of function overloading. That is, the startup code normally looks roughly like this:
extern int main(int argc, char *argv[], char *envp[]);
void entry() {
// OS-specific stuff to retrieve/parse command line, env, etc.
static_constructors();
main(argc, argv, envp);
execute(onexit_list);
static_destructors();
}
With your scheme, we'd need two separate pieces of startup code: one that calls main passing argc/argv, the other passing a std::vector<std::string>.
I should add that while this means the job isn't entirely trivial, it's still far from an insurmountable problem. Just for one example, Microsoft's linker already links different startup code depending on whether you've defined main or WinMain (or wmain or wWinMain). As such, it's obviously possible to detect the (mangled) name of the entry point the user has provided, and link to an appropriate set of startup code accordingly.
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
I have come to understand that char **envp is the third argument to main, and with the help of the code below, I was able to see what it actually contains.
int main(int argc, char *argv[], char *env[])
{
int i;
for (i=0 ; env[i] ; i++)
std::cout << env[i] << std::endl;
std::cout << std::endl;
}
My question is: why (in what situations) would programmers need to use this? I have found many explanations for what this argument does, but nothing that would tell me where this is typically used. Trying to understand what kind of real world situations this might be used in.
It is an array containing all the environmental variables. It can be used for example to get the user name or home directory of current logged in user. One situation is, for example, if I want to hold a configuration file in user's home directory and I need to get the PATH;
int main(int argc, char* argv[], char* env[]){
std::cout << env[11] << '\n'; //this prints home directory of current user(11th for me was the home directory)
return 0;
}
Equivalent of env is char* getenv (const char* name) function which is easier to use, for example:
std::cout << getenv("USER");
prints user name of current user.
The getenv()
function allows you to find the value of a specific environment variable, but doesn't provide a mechanism to scan over the entire list of environment variables. The envp argument allows you to iterate over the entire list of environment variables, as your demonstration code shows which is simply not feasible using the getenv() interface.
On POSIX systems, there is a global variable, extern char **environ;, which also points to the environment. The functions putenv() (ancient, non-preferred because it presents memory management problems), setenv() and unsetenv() can also manipulate the environment variable list (as defined by environ). A program can directly modify environ or the values it points at, but that is not advisable.
If you are using fork() and the exec*() family of functions, unless you use execve() and specify the environment explicitly, the child process will receive the environment defined by environ.
No header declares environ — AFAIK, it is the only variable defined by POSIX without a header to declare it. The C standard recognizes the int main(int argc, char **argv, char **envp) signature for main() as a common extension to the standard, documented in Annex J.
This is typically used to set configuration options or other information for a whole group of programs. Another use is to specify environment settings for a particular machine or user setup.
Well known examples are the PATH variable that contains the lookup pathes for executables, or the LD_LIBRARY_PATH variable that contains the pathes where to lookup the shared libraries.
env allows you to access the environment variables. It contains an array of strings. Examples are the users home directory, the configured language scheme, the PATH variable (where to look for directly executable programs?), ...
You can also set individual environment variables. For example, if you have testing (learning) and also a production system you deploy your application to. On one system you could set the variable "MY_APP_MODE=TEST" and on the other system you could specify "MY_APP_MODE=PROD". So you don't need to deploy different applications to the test and production systems. Your application could determine itself in what environment it is run.
Can we use the wmain() function with Unix compilers or it'll work only on/for Windows?
The only standard signatures for main are:
int main(void);
int main(int argc, char *argv[]);
However, a freestanding implementation can provide extensions/allow other signatures. But those are not guranteed to be portable. wmain looks like a Windows/VS thing. There's not much chance this will work on a *nix/GNU GCC.
The wmain signature exists in Windows to handle wide-character command line arguments. Generally, while Windows applications prefer UTF16, Unix applications prefer UTF8 for Unicode string encoding. UTF8 uses regular char character strings, so the standard main signature suffices for Unicode-aware Unix appications.
If you want to make a portable console application that does not require Unicode command line parameters, use main. If you do need Unicode command line parameters, then you need preprocessor directives that will enable the signature appropriate to each environment.
If you are making a cross-platform GUI application, use a special framework, like Qt.
wmain() is windows-specific. Just like _tmain, if that matters...
The only standard forms of main are
int main(void) { /* ... */ }
int main(int argc, char *argv[]) { /* ... */ }
What should main() return in C and C++?
All others are non-standard. If you read the document from MS you'll see that wmain is put in the Microsoft Specific section:
Microsoft Specific
If your source files use Unicode wide characters, you can use wmain, which is the wide-character version of main. The declaration syntax for wmain is as follows:
int wmain( );
int wmain(int argc, wchar_t *argv[], wchar_t *envp[]);
You can also use _tmain, which is defined in tchar.h. _tmain resolves to main unless _UNICODE is defined. In that case, _tmain resolves to wmain.
main function and command-line arguments
Its main purpose is to get Unicode parameters such as file names. However it's quite useless and most people don't actually use it because you can just call GetCommandLineW() and CommandLineToArgvW() to get the same thing without any changes to main's signature
For portability you can use Boost.Nowide so that everything is in UTF-8. Newer Windows 10 and MSVC's standard library also support setting UTF-8 as the active code page and you can get Unicode args with GetCommandLineA or sometimes with the normal main. See What is the Windows equivalent for en_US.UTF-8 locale?
See also
What is the difference between wmain and main?