Reputation: 7360
In my C code I want to expose static variables through inline functions , and this way avoid using 'extern' attribute, kind of OOP in standard C. However I cant compile it. Consider the following code:
$ cat object.h
inline int get_value(int index);
$ cat object.c
#include "object.h"
static int data_array[32];
inline int get_value(int index) {
return data_array[index];
}
$ cat app.c
#include "object.h"
void main(void) {
int datum;
datum=get_value(8);
}
$ gcc -c object.c
object.c:5:9: warning: ‘data_array’ is static but used in inline function ‘get_value’ which is not static
return data_array[index];
^
$ ls -l object.o
-rw-rw-r-- 1 niko niko 976 Aug 30 15:56 object.o
$ gcc -c app.c
In file included from app.c:1:0:
object.h:1:12: warning: inline function ‘get_value’ declared but never defined
inline int get_value(int index);
^
$ ls -l app.o
-rw-rw-r-- 1 niko niko 1368 Aug 30 15:56 app.o
$ gcc -o app app.o object.o
app.o: In function `main':
app.c:(.text+0xe): undefined reference to `get_value'
collect2: error: ld returned 1 exit status
Is it possible to access static variables somehow outside the file they have been declared through an inline function, that would be inlined in every .c file it is being used? Of course I can just declare the variable 'extern':
extern int data_array[];
and reference it directly but I want to do it through a function to simulate OOP in C without the overhead of a function call.
Upvotes: 2
Views: 1672
Reputation: 141554
Your code is illegal (in both ISO C and GNU C): the body of a function declared as inline
must appear in the same translation unit as any call to that function. But in your code it does not appear in app.c
, which is why you get the undefined reference error.
Further, as mentioned in comments, in ISO C an inline
function that is not also static
, may not mention an array with internal linkage. (I don't know what GNU C's rules are in this area).
In comments you talk about stuff like "overhead of CALL" etc. But this has little or nothing to do with the inline
keyword. The optimizer will produce the fastest possible code if you use an optimization switch. The purpose of the inline
keyword is to allow function bodies to appear in header files.
One option would be to unmark the function as inline
, and use the -O2 -flto
switches with gcc.
Another option is to use the inline
function but put the function body in the header file. In this case you will also need to use extern int data_array[];
etc, because it is not possible to define the array in the header file. Before doing this option then read this page. Here is some code that's compatible with both ISO C and GNU C:
// header file
extern int data_array[];
static inline int get_value(int index)
{
return data_array[index];
}
// source file
#include "header.h"
int data_array[32];
Upvotes: 4