So I recently just learned that instead of doing extern a variable and defining it in a cpp file. I can just inline the definition of the variable in a header and include it in any file and if I make changes to it in one it’ll show in the others. Just curious, is there a preferred way between the two or is it just preference? Or maybe a case where I’d need to use one over the other
#Extern vs inline variables
12 messages · Page 1 of 1 (latest)
When your question is answered use !solved or the button below to mark the question as resolved.
Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.
inline will copy the declaration to every translation unit (which the linker will then resolve) whereas extern will not
you’d usually want to inline if you’re defining something within the header itself
extern is for things that you want to be initialized outside the header
ideally you don't use either, because if you need it it means you have a global variable and that's annoying in and of itself
about the only acceptable globals would be "true" constants, in which case you'd lean towards inline constexpr I guess, assuming you can affort the constexpr
excluding that, many people prefer inline due to simplicity, but camila arlready mentioned some of the tradeof you should be considering
speaking of tradeofs, dealing with static order initialization fiasco and "duplication" of the variable across many binaries can be annoying
it's easier to control where a non-inline variable/object will actually end up in terms of binaries, because it's defined in a .cpp
really if the goal is to have a global state across functions it’s better practice to pass it around as a parameter
I'm not 100% positive on this, but I remember hearing that initialization of inline variables is deduplicated at runtime, not at link time