This is a fundamental question, but an important one none the less…
When starting a C++ program whose main method has the following common signature:
int main(int argc, char* args[]) { //Magic! return 0; }
is args[0] always guaranteed to be the path to the currently running program? What about cross platform (since I am in a Linux environment but may port later on.)?
It is not always. It’s the value that you gave the program by the Operation System. For example when starting a program using
execyou can set that to an arbitrary value:The first parameter is the file to start, and argv will contains argv[0] and all other parameters for main. envp contains the environment variables (not defined by Standard C or C++. This is a posix thing).
More precisely, this is the definition of argv in C++:
It’s pretty much up to the implementation what defines a ‘name used to invoke the program’. If you want to get the full path of your executable, you can use GetModuleFileName on Windows, and
argv[0](for getting the name used to execute, may be relative) together withgetcwd(for getting the current working directory, trying to make the name absolute).