Consider following source file:
#include <stdio.h>
int g_var_1;
int g_var_2;
// ...
void f1(void);
void f2(void);
// ...
int main(void)
{
f1();
f2();
return 0;
}
void f1(void)
{
// set the value of g_var_1
g_var_1 = 100;
}
void f2(void)
{
// read the value of g_var_1
printf("%d\n", g_var_1);
}
// ...
Is it possible to "apply promise" for some functions (within the same translation unit) that g_var_1 should be considered as read-only global variable for them? I have tried with something like:
void f2(void)
{
extern const int g_var_1;
// read the value of g_var_1
printf("%d\n", g_var_1);
}
but this yields into:
error: conflicting type qualifiers for ‘g_var_1’ extern const int
g_var_1;
Essentially I would like to restrict possibility of unintended modification of global variable in more complex code (values for real are known compile-time), still without "hooking" them as functions' paramaters, like as:
void f2(const int g_some)
{
printf("%d\n", g_some);
}
The appropriate way to do that is by separating your code into modules, and defining those globals as static, which will make them only module visible and will not export their symbol outside. You can then add a getter function to expose their value, without exposing them to modifications from outside the module.
Related
Let's assume I have 2 functions other than the main(), respectively func1() and func2(). Is it possible for me to call func1() in func(2) without declaring it first? Or should I use a pointer to the other function and pass it as an argument? Thanks in advance.
_"Is it possible for me to call func1() in func(2) without declaring it first?"_
It depends on compiler, but generally this will not work. (see exclusion example at bottom of answer.)
Some scenarios that illustrate:
Scenario 1: Normally will not work as function is being referenced before being declared:
int main(void)
{
int ret = func1();
return 0;
}
int func1(void)
{
return 1;
}
int func2(void)
{
return func1();
}
Results:
9, 15 error: implicit declaration of function 'func1' is invalid
in C99. Make sure that you include the function prototype.
Scenario 2: As all required definitions occur in order, this will compile and run without issue:
char func1(void)
{
return 1;
}
char func2(void)
{
return func1();
}
int main(void)
{
char ret = func1();
ret = func2();
return 0;
}
Results:
Compiles and runs with no problem because both functions are defined before being called (both func2() called from main() and func1() called from func1)
Scenario 3: The best way is always to pre-declare functions using prototypes either in same file before functions are called or in a header file that is #included in any source file that uses them. This clears up any potential problems, especially for those that inherit the code for maintenance:
int func1(void);
int func2(void);
int main(void)
{
int ret = func1();
return 0;
}
int func1(void)
{
return 1;
}
int func2(void)
{
return func1();
}
Regarding your comment:
"...a statement in my book caused confusion, I thought it might be related to a difference of the version of the C compiler in the book and I am using."
Could be: Per comment below, pre-standard C function definitions are supported by some modern compilers (eg gcc) thus would compile scenarios 1 & 2 without issue if functions complied with the default function definition; eg:
int func1(void)
int func2(void)
Here is how you do it:
void func2(int code); // forward declaration
void func1(const char* str)
{
func2(str[0]); // a call to a declared function
}
void func2(int code) // the callee
{
printf("code: %d\n", code);
}
I'd like to inline some functions, however, they are shared across the team and I don't want to force people to use them.
What would be the best way to add inline versions?
// normal
int func1();
int func2();
// inline versions
inline int inl_func1() { ... }
inline int inl_func2() { ... }
Would something like that make sense?
Edit:
Ideally:
I wouldn't have to write the same function definitions (function body) twice.
It would all be handled with s single define.
Declare/define the inline version and declare the non-inline version in the header file with different names.
// "func.h"
// normal
int func1(void);
int func2(void);
// inline versions
static inline int func1_inline(void) { ... }
static inline int func2_inline(void) { ... }
This allows a user to use either form or both. There is little compelling reason to use the same name and only allow one form.
Both can be handy for code that needs speed vs. space on some calls and not others.
This has a benefit that the one .c file that defines/implements func1(), func2() can use simple code to insure equivalent functionality.
#include "func.h"
int func1(void) {
return func1_inline();
}
int func2(void) {
return func2_inline();
}
BTW, declaring a function like int func1(); does not mean the same as int func1(void);. int func1(); means func1 returns an int, but provids no information about what can be passed to it. It is more like pseudo-code int func1(...);
Perhaps you could tell the people who want the inline functions to define a specific macro before including your header file:
#define WANT_INLINE_FUNC1
#include "awesome_funcs.h"
People who want the to call the externally linked function should omit the macro:
#include "awesome_funcs.h"
Then, in "awesome_funcs.h":
#ifdef WANT_INLINE_FUNC1
inline int func1(int param)
{
/* function body here */
}
#else
extern int func1(int param);
#endif
You also need to define a copy of the function with external linkage in one of your library files, e.g. in "awesome_funcs.c":
#define WANT_INLINE_FUNC1
#include "awesome_funcs.h"
/*
* This will define func1 with external linkage,
* but the function body is copied from the inline definition
* in "awesome_funcs.h".
*/
extern int func1(int param);
EDIT 1
You could combine this with chux's answer and get the best of both worlds (unless that makes things too confusing for your users). Just replace func1 in "awesome_funcs.h" with the following:
static inline int inl_func1(int param)
{
/* function body here */
}
#ifdef WANT_INLINE_FUNC1
inline int func1(int param)
{
return inl_func1(param);
}
#else
extern int func1(int param);
#endif
Then inl_func1 will always be the inline version, and func1 may or may not be inline, depending on whether or not the WANT_INLINE_FUNC1 macro was defined before including "awesome_funcs.h".
What would be the best way to add inline versions?
Your easiest course of action would be to declare static inline versions of these functions:
static inline int func1() { ... }
static inline int func3() { ... }
The function names do not need to differ from those of the corresponding external functions. However, if you #include a header that has declarations of functions with those names, then they must be compatible, AND there must be prior static declarations. For example:
static inline int func1(/* params */);
static inline int func3(/* params */);
#include "our_functions.h"
// ...
static inline int func1(/* params */) {
// implementation ...
}
static inline int func3(/* params */) {
// implementation ...
}
This will allow you to add inline versions without modifying your existing code that calls the external versions of these functions, and without affecting any other translation units. There is at least one alternative, but I don't see anything to recommend it over the above for your particular circumstances.
I'm trying to call other adjacent functions (delay() and delay_ex()) from a function (bitcheck()) as shown below and as expected, the compiler has thrown an error that delay() and delay_ex() functions weren't declared in the scope and I understood that we can't call functions other than from the main. So, I declared these delay() and delay_ex() functions in a header file and called from this program by including the header file, it worked well. So, is there any other such way to make this work?
void bitcheck()
{
int i;
for(i=0;i<NELEMS(array); i++)
{
delay();
AP_CMU->DIVIDER = freq_def[0];
encryption(array,i);
delay();
// LCD_DisplayUint32(i,0,array[i]);
AP_CMU->DIVIDER = freq_def[6];
delay_ex(10);
decryption(intr_array,i);
delay_ex(10);
// LCD_DisplayUint32(i,10,array[i]);
}
}
void delay()
{
int i;
for (i = 0; i < 100000; i++) {
__NOP();
}
}
void delay_ex(int j)
{
for(int s=0; s < j; s++)
{
for ( int i = 0; i < 10000; i++) {
__NOP();
}
}
}
You can write your functions above the code that calls them like:
void foo() {
}
void bar() {
}
int main () {
foo();
bar();
}
You can also forward declare functions like:
void foo();
void bar();
int main () {
foo();
bar();
}
void foo() {
}
void bar() {
}
Or you can put them in a header file and include it
file.h:
void foo();
void bar();
file.c:
#include "file.h"
int main () {
foo();
bar();
}
void foo() {
}
void bar() {
}
The compiler works in a single pass, as such when bitcheck() is parsed, the signatures of delay() and delay_ex() are not known, so the compiler cannot verify the call is type-correct.
The rule is declare or define before use; there are two possible solutions:
Define bitcheck() after the definition of delay() and delay_ex()
Forward-declare delay() and delay_ex().
By declaring the functions in a header and including it before defining bitcheck(), you used the second of these solutions, but use of an include file was not essential - #include does noting more than insert the file content into the translation-unit prior to compilation. This is useful when the symbols will be called from a different translation-unit than that in which they are defined; if that is not intended the declarations may be written directly rather then #include'd, and should also be declared static to avoid external-linkage and potential name clashes with other translation-units.
You need to define delay and delay_ex before bitcheck. Simply moving those two functions above bitcheck should suffice.
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.
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_*.
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.
I need to provide a C static library to the client and need to be able to make a struct definition unavailable. On top of that I need to be able to execute code before the main at library initialization using a global variable.
Here's my code:
private.h
#ifndef PRIVATE_H
#define PRIVATE_H
typedef struct TEST test;
#endif
private.c (this should end up in a static library)
#include "private.h"
#include <stdio.h>
struct TEST
{
TEST()
{
printf("Execute before main and have to be unavailable to the user.\n");
}
int a; // Can be modified by the user
int b; // Can be modified by the user
int c; // Can be modified by the user
} TEST;
main.c
test t;
int main( void )
{
t.a = 0;
t.b = 0;
t.c = 0;
return 0;
}
Obviously this code doesn't work... but show what I need to do... Anybody knows how to make this work? I google quite a bit but can't find an answer, any help would be greatly appreciated.
TIA!
If you're using gcc you can use the constructor attribute,
void runs_before_main(void) __attribute__((constructor))
{
...
}
From the gcc documentation
The constructor attribute causes the
function to be called automatically
be- fore execution enters main ().
Similarly, the destructor attribute
causes the function to be called
automatically after main () has
completed or exit () has been called.
Functions with these attributes are
useful for initializing data that will
be used implicitly during the
execution of the program.
You may provide an optional integer
priority to control the order in which
constructor and destructor functions
are run. A constructor with a smaller
priority number runs before a
constructor with a larger priority
number; the opposite relationship
holds for destructors. So, if you have
a constructor that allocates a
resource and a destructor that
deallocates the same resource, both
functions typically have the same
priority. The priorities for
constructor and destructor functions
are the same as those specified for
namespace-scope C++ objects
If you want to hide a struct from users, declare the struct in a header but define it in the c file, passing around pointers. As an example:
// foo.h
typedef struct private_foo foo;
foo * create_foo(void);
void free_foo(foo * f);
// foo.c
struct private_foo {
int i;
}
foo * create_foo(void){
foo * f = malloc(sizeof(*foo));
if (f) f->i = 1;
return f;
}
...
foo->i can then not be accessed outside foo.c.
If you want the client code to be able to use "t.a = ...", then you cannot hide the struct definition. What you want is called an opaque type, that will look something like this:
public.h:
struct foo;
set_a( struct foo *, int );
struct foo * new_foo(void);
main.c:
#include <public.h>
int main( void )
{
struct foo *k;
k = new_foo();
set_a( k, 5 );
}
The structure definition is only available to the library. If you do not make the library source code available, it is possible to completely hide it from the users of the library.
There is no portable way in C to ensure your code will run before main(). What I would do is just maintain an initialised flag in your library, set to false, and then refuse to do anything until your init function has been called.
As in:
static int initialised = 0;
int init (void) {
// do something.
initialised = 1;
return ERR_OK;
}
int all_other_functions (void) {
if (!init)
return ERR_NOT_INITED;
// do something.
return ERR_OK;
}