Finding current executable's path without /proc/self/exe

前端 未结 13 829
有刺的猬
有刺的猬 2020-11-22 01:06

It seems to me that Linux has it easy with /proc/self/exe. But I\'d like to know if there is a convenient way to find the current application\'s directory in C/C++ with cros

13条回答
  •  旧巷少年郎
    2020-11-22 01:37

    The whereami library by Gregory Pakosz implements this for a variety of platforms, using the APIs mentioned in mark4o's post. This is most interesting if you "just" need a solution that works for a portable project and are not interested in the peculiarities of the various platforms.

    At the time of writing, supported platforms are:

    • Windows
    • Linux
    • Mac
    • iOS
    • Android
    • QNX Neutrino
    • FreeBSD
    • NetBSD
    • DragonFly BSD
    • SunOS

    The library consists of whereami.c and whereami.h and is licensed under MIT and WTFPL2. Drop the files into your project, include the header and use it:

    #include "whereami.h"
    
    int main() {
      int length = wai_getExecutablePath(NULL, 0, NULL);
      char* path = (char*)malloc(length + 1);
      wai_getExecutablePath(path, length, &dirname_length);
      path[length] = '\0';
    
      printf("My path: %s", path);
    
      free(path);
      return 0;
    }
    

提交回复
热议问题