user1806687 user1806687 - 7 days ago 5
C Question

Inline function which returns a variable

I have the following structure:

test.h:

extern BOOL some_variable;

inline BOOL get_some_variable()
{
return some_variable;
}


test.c

BOOL some_variable = 10;
// some functions that change 'some_variable'.


main.c

int main()
{
while(1) {
if (get_some_variable()) { // do something }
}
}


My question is, will this work as expected. By that I mean will call in main get replaced by 'some_variable'? Or will this create copies of 'some_variable' or something like that? Does the inlined function need to be declared extern somewhere?

I am aware I could just be checking 'some_variable' in main.c without the need of a function, but this way seems more elegant to me. Or is there a better way, to have a variable in other source file returned without calling a function. I want this to reduce the number of operations needed to get 'some_variable' because this is for a microcontroller.

Answer

I've come to agree with @JonathanLeffler's conclusion that the form of inline function definition you present requires an external definition somewhere of function get_some_variable(), which is not provided by your test.h. It may turn out that your compiler still builds your program successfully, however, as it may well choose everywhere to use the provided inline function instead of the falsely promised external one.

Nevertheless, what you're doing seems a bit silly. The whole point of an inline definition of a function with external linkage is to provide an optional local alternative to the external function. If you want the inline function to be used always, then it would be appropriate to declare it static in test.h:

extern BOOL some_variable;

static inline BOOL get_some_variable()
{
    return some_variable;
}

One normally wants to avoid static declarations in headers, because they get duplicated in every translation unit that includes the header, but that's exactly what you want in a case such as this.

Or on the third hand, in this particular case you could consider just accessing the variable directly, which can be done from every translation unit anyway. If you're looking to encapsulate some_variable and restrict access to it, then you need a different approach.

Comments