emscripten-core / emscripten-core/emscripten

emscripten::val fails in global scope constructors

Open
#23,170 6 comments 0 reactions 0 assignees View on GitHub
Dominant language
C++
Stars
27.6k
Forks
3.6k
Avg merge
1d 1h
Merged PRs (30d)
105

Description

Tested with 3.1.73.

Attempting to use `val` in constructors executed at global scope (before `main` begins) fails with `emval::as has unknown type` errors.

Minimal example:

```cpp
#include
#include
#include

struct test_struct {
test_struct() {
std::cout << "nagivator.userAgent " << emscripten::val::global("navigator")["userAgent"].as() << std::endl;
std::cout << "window.innerWidth " << emscripten::val::global("window")["innerWidth"].as() << std::endl;
}
};

// fails when constructed in global scope:
test_struct test;

auto main()->int {
// OK :
//test_struct test;

// also OK:
//static test_struct test;

std::cout << "Hello world" << std::endl;
return EXIT_SUCCESS;
}
```
Build with `--bind` and `-sENVIRONMENT=web`.

Expected output, and output when test_struct is initialised inside `main`:
![image](https://github.com/user-attachments/assets/774d7be7-68da-4561-994a-ebdd2af0142a)

Output when trying to initialise at global scope, for the `.as()`:
![image](https://github.com/user-attachments/assets/cd04c0de-0def-493c-a2c4-d70799e87cee)
and for the `.as()`:
![image](https://github.com/user-attachments/assets/3b92a535-7c3c-46e6-9cf8-8c35415749c3)

I'm guessing that something gets initialised before `main` runs, but after static construction completes. Whereas ideally, everything should be ready before any C++ objects are constructed at static scope too.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.