Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice when referring to a program's name in C

What is considered best practice when referring to a program's name? I've seen:

#define PROGRAM_NAME "myprog"
printf("this is %s\n", PROGRAM_NAME);

as well as:

printf("this is %s\n", argv[0]);

I know, that the second approach will give me ./myprog rather than myprog when the program is not called from $PATH and that the first approach will guarantee consistence regarding the program's name.

But is there anything else, that makes one approach superior to the other?

like image 679
guest Avatar asked Jun 11 '10 17:06

guest


People also ask

How do you ask a name in C programming?

You need an array: char name[32]; or similar (and should use %31s in the format to avoid overflows). Also, with an array, you'll use just name (and not &name ) in the call to scanf() . And you should check that scanf() succeeded: if (scanf("%31s", name) == 1) printf("Your name is %s\n"); — adding a newline too.

What is good style in C?

C Style Guidelines. Meaningful names for variables, constants and functions. Do not use camelcase; use underscores for multi-word variables. For example, use hot_water_temperature instead of hotWaterTemperature.

Why do we use #in in C programming?

In C/C++, the # sign marks preprocessor directives. If you're not familiar with the preprocessor, it works as part of the compilation process, handling includes, macros, and more. It actually adds code to the source file before the final compilation.


2 Answers

The second approach is superior when you have multiple links. In *nix systems, sometimes behavior depends on how you call a program. So hard coding the program name would clearly be a problem -- it could never check that.

like image 61
MJB Avatar answered Oct 16 '22 02:10

MJB


I tried to take the best of both worlds:

char const * program_name;

int main(int argc, char **argv) {
   program_name = argv[0];
   //...
}

If you need program_name to be available in some other file you can declare it like this:

extern char const * program_name;

I declare "char const *" because I want it to be a pointer which points to const data. I'm not sure if I did right this part.

like image 37
user347594 Avatar answered Oct 16 '22 01:10

user347594