Question

In C++ I can have a getter function declared inline in a header file:

class Cpp_Example
{
  public:
    unsigned int get_value(void)
    { return value;}
  private:
    unsigned int value;
};

By including this header file, client methods and functions can use the getter function to access a private variable.

I'm looking to model this concept in the C language:
hello.h:

#ifndef HELLO_H
#define HELLO_H
#include <stdio.h>

inline void Print_Hello(void)
{
    extern const char hello_text[32];
    puts(hello_text);
}


inline void Print_Value(void)
{
    extern unsigned int value;
    printf("Value is: %d\n", value);
}

#endif // HELLO_H

hello.c:

const char hello_text[32] = "Hello World!\n";

static unsigned int value = 5U;

main.c:

#include <stdio.h>
#include <stdlib.h>

#include "hello.h"

int main(void)
{
    Print_Hello();
    Print_Value();
//  puts(hello_text);
    return EXIT_SUCCESS;
}

I get a linker error from gcc:

$ gcc -o main.exe main.c hello.c
/tmp/cc41ZB8H.o:main.c:(.rdata$.refptr.value[.refptr.value]+0x0): undefined reference to `value'
collect2: error: ld returned 1 exit status

Is there a way to have an inline function (in a header file) access a static variable in another translation unit?

Or is there a way to implement an inlined getter function?

I'm using IAR Embedded Workbench, ARM7TDMI processor on an embedded platform.
The gcc compiler is used to testing concepts on the PC.

Edit 1: Background
I'm looking to optimize getter calls that are inside a critical section. The objective is to reduce the time spent in the critical section.

Edit 2: No Globals
The Coding Guidelines our shop uses states no global variables.
Also, this system is an RTOS running MicroCOSII.

Was it helpful?

Solution

First of all, the same way you have private variables in C++, you probably mean to have private variables for a struct rather than global. With that assumption, here's one model you can use:

/* some_type.h */
struct some_type
{
    int public_data;
    void *privates;
};

struct some_type_privates
{
    char hello[32];
    int value;
};

inline const char *get_hello(struct some_type *t)
{
    struct some_type_privates *p = t->privates;
    return p->hello;
}

inline int get_value(struct some_type *t)
{
    struct some_type_privates *p = t->privates;
    return p->value;
}

/* similarly for setters */

The same way that your private variables and their getters and setters are in the header file, you can do it in C, too.


On the side, I'd like to recommend not to try coding C++ in C. While C++ likes to complicate things a lot to prevent the idiot from breaking something, C on the other hand trusts the programmer has some degree of intelligence. Whether these assumptions are justified are not the matter of discussion. But what I mean to say is that the spirit of C is not to hide a variable so that the programmer doesn't mistakenly access it.

That said, this is how you would normally make a struct in C:

struct some_type
{
    int public_data;
    char hello[32];     /* read only */

    /* internal */
    int value;
};

(with enough documentation of course) which tells any programmer that she shouldn't write over hello but can freely read it (what you were trying to achieve by an inline getter). It also tells that value is private so the programmer shouldn't read or write it.

You can see this in many POSIX functions that take or return a struct. Some that don't need to control the access let you freely modify the struct, such as stat. Some that do need to check the input have setters, such as pthread_attr_*.

OTHER TIPS

You need to remove the static keyword. static definitions are local to the compilation unit.

As Shabbas wrote, it doesn't really work that way in C. The keyword inline implies static, even if the compilers doesn't actually inline it. If it is such a short function, it will probably inline it. But the point is, if it would not be static, it could not even consider inlineing it, as the function would need to be visible externally, it would need an address, which an inlined function doesn't have. Since it is local in your compilation unit, it can only work on stuff known inside that compilation unit. Thus you need to say something about that value variable, much like you do need to mention it in the C++ header as well, only in C there is no such thing as private . You can not have Inlineing and data hiding in the same case, neither in C, nor in C++.

Assuming you mean for global, statically-allocated variables you can do this:

In Example.h:

#ifndef Example
#define Example
  extern int getValue();
#endif

In Example.c

#include "Example.h"

static int value;

inline int getValue() {
    return value;
}

// All the functions in Example.c have read/write access

In UsesValueExample.c

#include "Example.h"

// All the functions in UsesValueExample.c have read-only access

void printValue() {
    printf("value = %d", getValue());
}

If you want to get fancy and force all code to access through a getter and setter, e.g. if the variable is volatile and you want to heavily encourage all the methods to use a local cache of the variable to avoid the overhead of accessing the volatile, then:

In VolatileExample.h:

#ifndef VolatileExample
#define VolatileExample
  extern int getValue();
#endif

In VolatileExample.c

#include "VolatileExample.h"

void setValue(); // Forward declaration to give write access

// All the functions in VolatileExample.c have read/write access via getters and setters

void addToValuesAndIncrementValue(int const values[], int const numValues) {
    int value = getValue(); // Cache a local copy for fast access

    // Do stuff with value
    for (int i = 0; i < numValues; i++) {
        values[i] += value;
    }
    value++;

    // Write the cache out if it has changed
    setValue(value);
}

// Put the definitions after the other functions so that direct access is denied

static volatile int value;

inline int getValue() {
    return value;
}

inline void setValue(int const newValue) {
    value = newValue;
}

In UsesVolatileValueExample.c

#include "VolatileExample.h"

// All the functions in UsesVolatileValueExample.c have read-only access

void printValue() {
    printf("value = %d", getValue());
}

Here is a pattern I've been using to hide global variables.

Inside some header file, such as module_prefix.h, you declare the following:

typedef int value_t;  // Type of the variable

static inline value_t get_name(void)    __attribute__((always_inline));
static inline void    set_name(value_t) __attribute__((always_inline));

static inline value_t get_name(void) {
    extern value_t module_prefix_name;
    return module_prefix_name;
}

static inline void set_name(value_t new_value) {
    extern value_t module_prefix_name;
    module_prefix_name = new_value;
}
/* Note that module_prefix_name is *no longer* in scope here. */

Then of course you have to define module_prefix_name in some compilation unit, without the static keyword, as discussed above, e.g. in module_prefix.c you have the following:

#include "module_prefix.h"
value_t module_prefix_name = MODULE_PREFIX_NAME_INIT_VALUE;

This is essentially the same pattern that Thomas Matthews tried to use, drilling down to the essence and making sure that the compiler inlines the functions always and does not unnecessarily generate explicit function bodies. Note the use of module_prefix as poor man's name spaces.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top