0

This question is just out of curiosity. I thought there might be a predefined macro or something but couldn't find anything. If impossible, is it appropriate to use a constant global variable initiated with argv?

I really don't know why the question was closed. The stated justification is that an answer already exists here:Finding current executable's path without /proc/self/exe

The referred question has platform-specific answers and is also tagged with C++, which is a whole different story on the topic with boost. I just tagged C and compiler-constants just in case there is a method I didn't know about to accomplish the task of keeping track of the executable file identifier.

  • 2
    No. argv is a runtime value. there may be other ways that are platform-dependent. – OldProgrammer Mar 09 '22 at 18:04
  • 3
    There is no way this can be known in compile time. You can rename the executable after it was compiled. – Eugene Sh. Mar 09 '22 at 18:05
  • It would be system dependent. For example, on most Unixes you could look up the process ID in [/proc](https://www.kernel.org/doc/html/latest/filesystems/proc.html) and get the executable name. – Schwern Mar 09 '22 at 18:06
  • @EugeneSh. I thought about that too but wouldn't it be okay to assign argv[0] to whatever runtime constant you want. Since no one wants to work with global vars, I think that would be a good idea. – Omer Erbilgin Mar 09 '22 at 18:08
  • @Schwern frankly speaking, if you're not coding cross-platform and dealing with platform-specific libraries, system calls, etc., just use bash. GNU core utils just work fine. – Omer Erbilgin Mar 09 '22 at 18:10
  • @OmerErbilgin "runtime constant" seems like an oxymoron, what do you mean by that? What problem are you trying to solve? – Schwern Mar 09 '22 at 18:44
  • @Schwern for example if the gcc compiler pointed argv[0] to a char *, wouldn't that be a runtime constant? – Omer Erbilgin Mar 09 '22 at 18:48
  • @OmerErbilgin You can do `const char *exename; int main(int argv, char **argv) { exename = argv[0]; ... }`, but now you've got a global variable. – Schwern Mar 09 '22 at 19:11
  • @Schwern Exactly, but would you consider this good practice? I would consider appropriate argument parsing using a separate file/function without passing argv or using an extend (using getopt maybe). – Omer Erbilgin Mar 10 '22 at 11:32
  • @OmerErbilgin Depends why you need it. If it's just for argument parsing, probably not. If you need the executable name globally for some reason, maybe. – Schwern Mar 10 '22 at 17:19

0 Answers0