Alan Alan - 6 days ago 6
C Question

How to get the name of the executed file after compilation with gcc?

I'm coding a program in C, and I'd like it to detect its own name. I'll explain :

I want it to do a specific action, depending of its name. Let's say :

if (!strcmp(myName, "Program1"))
printf("I am program 1!");
else
printf("I am someone else !");


This code is contained in Program1.c, and is compiled with :

gcc Program1.c -o Program1


And I'd execute it with :

./Program1


But I'm not able to find the code that would allow me to get the value "Program1" (the name of the executable file), which would be the variable myName in the code I gave.

Can someone help me please?

Answer

The name of the output from gcc is not stored anywhere in the file by default, and I don't know of a way to inject it into the binary. But is this what you really want?

The name that the program is invoked as is available as argv[0]. That may be different if the executable has been renamed after compilation.

#include <stdio.h>
int main(int argc, char *argv[]) {
    printf("My name is %s\n", argv[0]);
    return 0;
}

Argument 0 is chosen by the calling program. It can be a full path with directory information (it typically depends whether the caller performed PATH lookup or invoked the executable from an explicit location), so if you want to act based on that, you should probably strip the path information (e.g. with basename on Unix/POSIX platforms).

Argument 0 is chosen by the caller, so it's a matter of convention. But it's a pretty much universally followed convention, except when the caller has a good reason not to respect it. Most platforms have a way to locate the executable. For example, on Linux, /proc/self/exe is a symbolic link to the executable. But in most cases, if the caller passes a different name, that means that the caller wants your program to behave as that different name, so argv[0] is what you should use.

argv[0] can be NULL if the program is invoked without arguments (i.e. if argc is 0). That's rare, but for robustness your program should do something sensible in that case.

Comments