Build Environment:
- Visual Studio 2022
- Windows 10 64-bit
- C++ Standard : C++20
I am trying to get the directory of my executable file. In my earlier code based on C++17 standard I could read the path using std::filesystem::current_path().string()
and store it in a global static std::string object. In my new C++20 project (fist for the standard) I am returned empty string in my global static std::string object, however in the local object I created to store path it is successfully storing executable path.
Source file:
std::filesystem::path path = std::filesystem::current_path();
std::string path_string = path.string(); //Working - Path is stored in string variable
Common::directory_path = path.string(); //Not Working - Empty string string variable
std::string path_temp = std::filesystem::current_path().string(); //Working - Path is stored in string variable
Common::directory_path1 = std::filesystem::current_path().string(); //Not Working - Empty string string variable
Header file:
namespace Common
{
static std::string directory_path{ "" };
}
Edit :
I have added my complete code. I have included Common.h in all my other classes (header file for the class) and imported the class header in respective source file.
#include "Common.h"
#include <plog/Appenders/ColorConsoleAppender.h>
bool Common::app_init(void)
{
try
{
Common::plog_init();
std::filesystem::path path = std::filesystem::current_path();
std::string path_string = path.string(); //Working - Path is stored in string variable
Common::directory_path = path.string(); //Not Working - Empty string string variable
std::string path_temp = std::filesystem::current_path().string(); //Working - Path is stored in string variable
Common::directory_path = std::filesystem::current_path().string(); //Not Working - Empty string string variable
return true;
}
catch (const std::exception& ex)
{
LOG_ERROR << ex.what();
}
return false;
}
Header:
#pragma once
#include <any>
#include <tuple>
#include <mutex>
#include <array>
#include <queue>
#include <chrono>
#include <string>
#include <vector>
#include <thread>
#include <vector>
#include <memory>
#include <atomic>
#include <variant>
#include <sstream>
#include <optional>
#include <coroutine>
#include <cpr/cpr.h>
#include <algorithm>
#include <filesystem>
#include <functional>
#include <plog/Log.h>
#include <json/json.h>
#include <unordered_map>
#include <pystring/pystring.h>
//#include <sigc++-3.0/sigc++/sigc++.h>
#include <boost/algorithm/string.hpp>
namespace Common
{
static std::string directory_path{ "" };
constexpr std::size_t error_file_size = 1024 * 1024 * 100; //100 M.B.
const int max_error_files = 5;
bool app_init(void);
bool plog_init(void);
};
main.cpp
#include "Common.h"
int main()
{
Common::app_init();
PLOG_INFO << Common::directory_path;
}