@@ -26,6 +26,7 @@ namespace cpp2rust {
2626std::unordered_map<std::string, std::string> Converter::inner_structs_;
2727std::unordered_set<std::string> Converter::decl_ids_;
2828std::unordered_set<std::string> Converter::globals_;
29+ std::vector<std::string> Converter::global_inits_;
2930std::unordered_set<std::string> Converter::abstract_structs_;
3031Converter::RecordIndex Converter::record_decls_;
3132std::map<std::string, Converter::MethodsOnPtr> Converter::methods_on_ptr_;
@@ -74,6 +75,23 @@ std::string Converter::EmitMethodsOnPtr() {
7475 return out;
7576}
7677
78+ std::string Converter::ForceGlobalInit (const clang::VarDecl *decl) {
79+ return std::format (" std::cell::LazyCell::force(&*&raw const {});" ,
80+ GetNamedDeclAsString (decl));
81+ }
82+
83+ std::string Converter::EmitGlobalInits (Model model) {
84+ std::string out = model == Model::kUnsafe
85+ ? " pub unsafe fn __cpp2rust_init_globals() {\n "
86+ : " pub fn __cpp2rust_init_globals() {\n " ;
87+ for (const auto &line : global_inits_) {
88+ out += line;
89+ out += ' \n ' ;
90+ }
91+ out += " }\n " ;
92+ return out;
93+ }
94+
7795std::string Converter::EmitOpaqueRecords () {
7896 std::string out;
7997 record_decls_.ForEachUndefined ([&](const std::string &name) {
@@ -512,6 +530,7 @@ bool Converter::ConvertVarDeclSkipInit(clang::VarDecl *decl) {
512530 StrCat (AccessSpecifierAsString (decl->getAccess ()), keyword::kStatic ,
513531 keyword_mut_);
514532 ENSURE (decl_ids_.insert (GetID (decl)).second );
533+ global_inits_.push_back (ForceGlobalInit (decl));
515534 } else if (decl->isStaticLocal ()) {
516535 StrCat (keyword::kStatic , keyword_mut_);
517536 } else if (decl->isLocalVarDecl ()) {
@@ -4180,14 +4199,15 @@ pub fn main() {{
41804199 let mut argv: Vec<*mut libc::c_char> = args.iter().map(|arg| arg.as_ptr() as *mut libc::c_char).collect();
41814200 argv.push(::std::ptr::null_mut());
41824201 unsafe {{
4202+ __cpp2rust_init_globals();
41834203 ::std::process::exit(main_0((argv.len() - 1) as i32, argv.as_mut_ptr()) as i32)
41844204 }}
41854205}})" ,
41864206 main_function_name));
41874207 } else {
4188- StrCat (std::format (
4189- " pub fn main() {{ unsafe {{ std::process::exit({}() as i32); }} }}" ,
4190- main_function_name));
4208+ StrCat (std::format (" pub fn main() {{ unsafe {{ __cpp2rust_init_globals(); "
4209+ " std::process::exit({}() as i32); }} }}" ,
4210+ main_function_name));
41914211 }
41924212}
41934213
0 commit comments