====== get_CurrentExecutable() ====== Filename des gerade ausgeführten Moduls herausfinden Hier soll man zwischen (mindestens) zwei Situationen unterscheiden, da die Vorgehensweise etwas unterschiedlich ist: * Das Programm selbst (wie z.B. ein EXE bzw. PE-Modul unter Windows) * Dynamische Library / Shared Object (wie z.B. ein SO-Modul unter Unix bzw. DLL unter Windows) ===== Im Fall "Das Programm selbst" ===== Man nimmt am Anfang der **main()** den Parameter **argv[0]** und speichert den dort enthaltenen Wert in einer lokalen/globalen Variable ab: Schritt 1: in einem separaten Modul definiert man die Zugriffsfunktionen: char current_executable[PATH_MAX] = { 0 }; string get_current_executable() { return current_executable; } void set_current_executable(char *executable_fq_path) { if (current_executable[0] == '\0' && strlen(executable_fq_path) > 0) { strncpy(current_executable, executable_fq_path, sizeof(current_executable)); current_executable[sizeof(current_executable) - 1] = '\0'; } } // set_current_executable() Schritt 2: innerhalb von main() findet die Initialisierung statt: int main(int argc, char* argv[]) { char current_executable_fqPath[PATH_MAX] = { 0 }; if (realpath(argv[0], current_executable_fqPath) == NULL) current_executable_fqPath[0] = '\0'; set_current_executable(current_executable_fqPath); } // main() :!: Unter **Windows** kann man den Schritt 2 ersparen (und den Setter auch), weil das API eine passende Funktion zur Verfügung stellt: string get_current_executable() { char path[MAX_PATH]; HMODULE hModule = GetModuleHandle(NULL); if (hModule != NULL) { GetModuleFileName(hModule, path, (sizeof(path))); return path; } return ""; } :!: Die Makros **PATH_MAX** (Unix) und **MAX_PATH** (Windows) in den jeweiligen APIs vordefiniert. ===== Im Fall "Dynamische Library" ===== Unter Windows die gleiche Vorgehensweise wie oben. Für Unix wird der Modulname innerhalb der Initialisierungsroutine (wird durch **%%void __attribute__ ((constructor))%%** festgelegt) ermittelt: #define _GNU_SOURCE #include #include void __attribute__ ((constructor)) lib_initialize(void); void __attribute__ ((destructor)) lib_finalize(void); // Called when the library is loaded and before dlopen() returns. void lib_initialize(void) { Dl_info dl_info; dladdr((void *) lib_initialize, &dl_info); set_current_executable(dl_info.dli_fname); } // lib_initialize() // Called when the library is unloaded and before dlclose() returns. void lib_finalize(void) { } Quelle: [[http://stackoverflow.com/questions/1681060/library-path-when-dynamically-loaded]] ---- Stand: 05.09.2016\\ --- //[[feedback.jk-wiki@kreick.de|: Jürgen Kreick]]// EOF