Skip to content

Commit

Permalink
fix: reading vars from win32 api when using msvc
Browse files Browse the repository at this point in the history
  • Loading branch information
zaucy committed Aug 22, 2024
1 parent b804e4a commit 39dad10
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 4 deletions.
2 changes: 1 addition & 1 deletion build.cmd
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ cl /nologo ^
/std:c++latest /W4 /MDd /EHsc ^
/reference "%modules_dir%\std.ifc" ^
/reference "%modules_dir%\std.compat.ifc" ^
/c "%root_dir%.cache\cpp2\source\_build\cpp2b.ixx" > NUL
/c "%root_dir%.cache\cpp2\source\_build\cpp2b.ixx"
popd

if %ERRORLEVEL% neq 0 (
Expand Down
30 changes: 28 additions & 2 deletions share/cpp2b.cppm.tpl
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,17 @@ module;
# include <stdlib.h>
#endif

extern char **environ;

export module cpp2b;

import std;
import std.compat;

#ifdef _MSC_VER
extern char **_environ;
#else
extern char **environ;
#endif

export namespace cpp2b {
enum class platform { linux, macos, windows };
Expand Down Expand Up @@ -69,15 +73,33 @@ inline auto set_var(const std::string& name, const std::string& value) -> void {
#endif
}

inline auto set_var(auto name, auto value) -> void {
return cpp2b::env::set_var(std::string{name}, std::string{value});
}

inline auto get_var(const std::string& name) -> std::optional<std::string> {
#if defined(_MSC_VER)
auto val = std::string{""};
val.resize(GetEnvironmentVariableA(name.c_str(), val.data(), 1) - 1);

if(!val.empty()) {
GetEnvironmentVariableA(name.c_str(), val.data(), val.size() + 1);
return val;
}
#else
auto val = std::getenv(name.c_str());
if(val != nullptr) {
return std::string{val};
}
#endif

return {};
}

inline auto get_var(auto name) -> std::optional<std::string> {
return cpp2b::env::get_var(std::string{name});
}

export class vars {
public:
struct entry {
Expand Down Expand Up @@ -150,7 +172,11 @@ public:
};

iterator begin() const noexcept {
#ifdef _MSC_VER
return iterator(_environ);
#else
return iterator(environ);
#endif
}

iterator end() const noexcept {
Expand Down
2 changes: 1 addition & 1 deletion src/main.cpp2
Original file line number Diff line number Diff line change
Expand Up @@ -278,7 +278,7 @@ build_cpp1_module: (name: std::string, sources, module_deps) = {
}

has_env: (var_name: *const char) -> bool = {
return std::getenv(var_name) != nullptr;
return cpp2b::env::get_var(var_name).has_value();
}

has_msvc_env_vars: () -> bool = {
Expand Down

0 comments on commit 39dad10

Please sign in to comment.