Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

If it was "relatively easy" then there wouldn't be a million dependency injection solutions for Java of ungodly runtime cost to try and solve this problem.

People want to initialize stuff at load library time. They will always want to do this. If the language doesn't provide a solution, people will just bolt on shitty add-on toolchains to do it anyway.

This isn't a uniquely C++ problem (__attribute__((constructor)) is after all for C, not C++).

Take for example Rust, which also doesn't provide an attribute((constructor)) equivalent and says nothing happens before or after main. Except https://crates.io/crates/ctor exists to immediately say "fuck that noise" and racked up >20m downloads.



> If it was "relatively easy" then there wouldn't be a million dependency injection solutions for Java of ungodly runtime cost to try and solve this problem.

You realize Java has the feature you're discussing, without dependency injection?

   class Foo {
      static {
           initialize();
      }
    }

They even have a well defined execution order:

https://docs.oracle.com/javase/specs/jls/se8/html/jls-14.htm..., section 8.7, with order defined in section 12.4


That runs at class load time, not at library/executable load time as c++ static constructors or __attribute__((constructor)) does.

So no, that's not equivalent. Not even close. This is why you see things in Java that scan through loaded jars looking for all classes with attributes to just speculatively load. To recreate what c++ has natively & C has with a broadly supported extension.




Consider applying for YC's Fall 2025 batch! Applications are open till Aug 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: