Hacker News new | ask | show | jobs
by knorker 1911 days ago
Many languages do.

A Python import will execute anything it imports (most of what's "executed" is "def" and "class"), but if there's code at the top level, it'll run.

C++ will run constructors for global variables before main().

Even C has side-effects from linking in!

    void __attribute__ ((constructor)) init() {}
So I don't mean side-effects at compile time (e.g. it's not like C macros), but importing / linking something even if you don't use it is very common that it has side effects.

Why would you do this? Commonly to "register a handler", to not have to both "import foo" and call "foo.init()"

1 comments

To be honest, I think of header files really lowly.

I do see now why would one use that, thank you! Though I still think that adding an explicit keyword to run init functions would be preferable, like `import init package`.

That's what the underscore is. :-)

Other init code is stuff like "var foo = regexp.MustCompile(...)".

Then there may be transitive imports that do C code, and it really needs to run its init code.