2

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?

3
  • 1
    For a start, in C you cannot compare strings with myName=="Program1". But in main, you can check argv[0] which is the executable name (possibly with path too). Commented Nov 29, 2016 at 19:10
  • Yep, sorry, I was tired & wanted to make what I wanted clear, but it is indeed incorrect. Thanks for your answer! Commented Nov 29, 2016 at 19:34
  • In MSVC argv[0] contains exactly what I typed at the console, for example test.exe or ..\ctest\test and when I run it from the GUI it gives F:\Work\CTEST\test.exe. So your name matching needs to be rather careful ;) Commented Nov 29, 2016 at 19:41

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot for your answer, I think I'll be able to work around that !

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.