Program name: Difference between revisions

From Rosetta Code
Content added Content deleted
No edit summary
No edit summary
Line 17: Line 17:
To get the source information about some part of code, use compiler defined macros. Most compilers support them or some variation of.
To get the source information about some part of code, use compiler defined macros. Most compilers support them or some variation of.
<lang c>#include <stdio.h>
<lang c>#include <stdio.h>

int main()
int main()
{
{
printf("This code was in file %s in function %s, at line %d\n",
printf("This code was in file %s in function %s, at line %d\n",
__FILE__, __FUNCTION__, __LINE__);
__FILE__, __FUNCTION__, __LINE__);
return 0;
}</lang>

To get the executable's name, use argv.

<lang c>#include <stdio.h>

int main(int argc, char **argv) {
char *program = argv[0];
printf("Program: %s\n", program);

return 0;
return 0;
}</lang>
}</lang>
Line 33: Line 44:


int main(int argc, char **argv) {
int main(int argc, char **argv) {
cout << "Executable: " << argv[0] << endl;
char *program = argv[0];
cout << "Program: " << program << endl;


return 0;
return 0;

Revision as of 00:45, 6 August 2011

Program name is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

It is useful to programmatically access a program's name, e.g. for determining whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".

Examples from GitHub.

C

It might not be very useful for a C program to access source filenames, because C code must be compiled into an executable, and anything could have happened to the source file after the compilation. However, C can access the executable's filename.

<lang c>#include <stdio.h>

int main(int argc, char **argv) { printf("Executable: %s\n", argv[0]);

return 0; }</lang>

To get the source information about some part of code, use compiler defined macros. Most compilers support them or some variation of. <lang c>#include <stdio.h>

int main() { printf("This code was in file %s in function %s, at line %d\n", __FILE__, __FUNCTION__, __LINE__); return 0; }</lang>

To get the executable's name, use argv.

<lang c>#include <stdio.h>

int main(int argc, char **argv) { char *program = argv[0]; printf("Program: %s\n", program);

return 0; }</lang>

C++

C++ has difficulty accessing source code filenames, because C code must be compiled into an executable. However, C++ can access the executable's filename.

<lang cpp>#include <iostream>

using namespace std;

int main(int argc, char **argv) { char *program = argv[0]; cout << "Program: " << program << endl;

return 0; }</lang>

Perl 6

In Perl 6, the name of the program being executed is in the special global variable $*PROGRAM_NAME. <lang perl6>say $*PROGRAM_NAME;</lang>