不用自己寫代碼,errno.h中提供了兩個可直接使用的全局變量,GCC預設打開了宏_GNU_SOURCE:
(CUtils::get_program_name(); CUtils::get_program_short_name();)
<a href="https://github.com/eyjian/mooon/blob/master/common_library/include/mooon/sys/utils.h" target="_blank">https://github.com/eyjian/mooon/blob/master/common_library/include/mooon/sys/utils.h</a>
const char* CUtils::get_program_name()
{
//#define _GNU_SOURCE
//#include errno.h>
return program_invocation_name;
}
const char* CUtils::get_program_short_name()
return program_invocation_short_name;
效果代碼(g++ -g -o x x.cpp):
//#define _GNU_SOURCE
#include errno.h>
#include stdio.h>
int main()
printf("program_invocation_name: %s\n", program_invocation_name);
printf("program_invocation_short_name: %s\n", program_invocation_short_name);
return 0;
運作結果:
# /tmp/X/x
program_invocation_name: /tmp/X/x
program_invocation_short_name: x