Browse Source

Add code to detect executable path

Xi Ruoyao 5 years ago
parent
commit
eb5f2ce1bf
2 changed files with 51 additions and 0 deletions
  1. 42 0
      executable.cc
  2. 9 0
      executable.hpp

+ 42 - 0
executable.cc

@@ -0,0 +1,42 @@
+#include "executable.hpp"
+
+#ifdef __linux__
+
+#define _EXEC_PATH_IMPL_ 1
+
+#include <unistd.h>
+#include <string>
+#include <climits>
+
+boost::filesystem::path get_executable_path()
+{
+	static char buf[PATH_MAX];
+	readlink("/proc/self/exe", buf, PATH_MAX);
+	return buf;
+}
+
+#endif
+
+#ifdef __WINNT__
+
+#define _EXEC_PATH_IMPL_ 1
+
+#include <windows.h>
+
+boost::filesystem::path get_executable_path()
+{
+	static char buf[MAX_PATH];
+	GetModuleFileNameA(NULL, buf, MAX_PATH);
+	return buf;
+}
+
+#endif
+
+#ifndef _EXEC_PATH_IMPL_
+#error "don't know how to get executable path"
+#endif
+
+boost::filesystem::path get_executable_directory()
+{
+	return get_executable_path().parent_path();
+}

+ 9 - 0
executable.hpp

@@ -0,0 +1,9 @@
+#ifndef _EXECUTABLE_HPP_
+#define _EXECUTABLE_HPP_
+
+#include <boost/filesystem.hpp>
+
+extern boost::filesystem::path get_executable_path(void);
+extern boost::filesystem::path get_executable_directory(void);
+
+#endif