0

A variable defined with inline keyword in C++ allows definition of the variable in multiple compilation units and lets linker to resolve these multiple definitions into a single one, as it is explained here: https://stackoverflow.com/a/47502744/14721148

Is it possible to define a variable with inline keyword in C in order to achieve the same behavior as in C++? If not, is there any workaround in C language?

cerveka2
  • 156
  • 7
  • 3
    In C inline is only a function specifier. – Vlad from Moscow May 05 '23 at 12:21
  • 1
    If you are using Clang or GCC and associated tools, you can declare objects with tentative definitions (declare an object at file scope without `extern` and without initialization, as in `int x;`) and compile with `-fcommon`, and all the definitions resulting from the tentative definitions will be coalesced into a single definition. There can also be one regular definition marked by using initialization, as in `int x = 3;`. – Eric Postpischil May 05 '23 at 12:54
  • 1
    The correct solution in either language is to not do spaghetti programming with global variables, but instead communicate between different parts of the program through setter/getter functions. – Lundin May 05 '23 at 13:43
  • The correct way (in C) is to include a(n external) *definition* in exactly one translation unit, and to provide only *declarations* in other TUs where access to that variable is wanted. That works fine in C++, too, and I would rate it stylistically superior to using `inline` variables in that language. Though more generally, either approach is usually still a bad idea. – John Bollinger May 05 '23 at 13:49

0 Answers0