Is there any standardized structure of C source and header files?
I'm thinking about something like this (example for C source file):
// static variables
// public variables
// static methods
// public methods
This is a totally subjective question. However, here's what I do approximately.
Header:
// extern defines, constants and enums
// public types
// extern methods
There are no extern variables :-)
Compilation unit:
// includes
// definitions for extern constants
// static function prototypes
// everything else
I tend to group things that are related together, so I don't rigidly put all of the static variables or defines in oner place, but near where they are going to be used.
Given that this is a C question, I presume:
// static variables
// public variables
// static methods
// public methods
... means:
// static variables
// public variables (external linkage)
// static functions
// public functions
As for the order, I don't think you can evoke anything but a subjective response about this. It is certainly not standardized unless you are asking about a specific organization's coding standards, in which case they might have policies about this. Some might prefer privates before publics, others publics before privates. Some might put one before the other to emphasize the importance of one over the other, while others might put it after to emphasize the important over its predecessor. There's no unanimous agreement about these kinds of stylistic preferences and they have no logical effect on the code or its runtime behavior.
The important thing is to be consistent and I'd recommend avoiding anything very exotic as it will scare away other developers who have to look at your code. Exotic styles are usually bad if you want to work with other engineers. The more exotic styles become, the more uniquely personal they are the more they demand of others to adjust to personal preferences.
Do try to cut down on the number of public variables with external linkage (global variables). As small a difference as it sounds, it's a big step up to write a public function to fetch a variable, even if it's simple getter-type function which returns a pointer to the variable, as it'll at least allow you to modify that code if a change ever becomes necessary and also allow you to easily put breakpoints wherever it is accessed, add instrumentation to the function, etc.
I usually use the following for c:
// include guard
#ifndef <filename>_H
#define <filename>_H
// define this as extern for c++
#ifdef __cplusplus
extern "C" {
#endif
#include <libraries>
#define <preproc variables>
#define <preproc macros>
enum <enums> {
};
typedef <variables>;
typedef <structs>;
function prototypes();
// end c++ guard
#ifdef __cplusplus
}
#endif
// end include guard
#endif
The structure you are using is good.
Best practice is with regards to naming the public variables and public methods, prefix the same with the product's name / company's name to avoid naming conflict with other libraries.
Related
I just spotted this in the legacy code. I know that using the macro, whenever the name is used, it is replaced by the contents of the macro. They are most commonly used to give symbolic names to numeric constants.What I know is preprocess has no notion of type safety, scope.
What is the real benefit of doing like this?
#define STATIC static
STATIC function1() { /*Do something*/ }
I knew that static functions are visible only in that module or translation unit. Not visible outside of the C file they are defined.
Why not just declare like this, instead of macro replacement?
static function1() { /*Do something*/ }
I thought I will find an answer in SO but I didn't find any proper answer.
There is no rational reason why you would do this. Generally it is bad practice to hide keywords behind #define in this manner, because the code turns cryptic and harder to read.
I would suspect it has to do with coding style, it is common to write various function specifiers in upper case, particularly in Windows programming. Often it is done to specify a certain calling convention. For example CALLBACK in Windows, or this example from the old "Windows bible" (Petzold):
#define EXPORT __declspec (dllexport)
(Which could be modified to also contain extern "C" in case of C++.) You'd then have a function such as EXPORT void CALLBACK func (void). Similarly there's also WINAPI in Windows.
Sometimes we also see things like
#define PRIVATE static
which is kind of horrible, because static doesn't really have the same meaning as private in C++.
I am using unity for unit testing.
I have a header throughout my project that I include with some helper macros, like an assert wrapper that I can use to track which assert fired.
In that header I also have the following definition:
#define static //nothing
I learned that little trick from this article:
http://www.embedded.com/design/programming-languages-and-tools/4007177/2/Doing-C-code-unit-testing-on-a-shoestring-Part-1-The-basics-and-the-tools
This allows me to write unit tests for static functions and it allows me to access any relevant file scope data from my test harness.
The trouble is this totally breaks static at the function scope. The article goes on to say if I do this:
#define static extern
Then any variable that is static at the function scope can then be defined within the test harness. We're off to the races, right? Not exactly.
Because the following occurs
void foo()
{
extern bool my_flag = false;
}
Now we are supplying an initializer to declaration, which is invalid. So that means any static variable I handled this way would inherently need to be initialized after startup.
Because static variables within functions are relatively uncommon, I thought I might circumvent this by defining a new symbol, LOCAL_STATIC. So now in my header I have the following
#define static extern
#define LOCAL_STATIC static
But that does not work because those directives are evaluated strictly in order - #define LOCAL_STATIC static becomes #define LOCAL_STATIC extern, or at least that is what seems to be happening. Because LOCAL_STATIC produces the same error and indeed ends up getting changed to extern by the preprocessor.
So is there any way around this?
AFAIK anything like this is impossible:
#define LOCAL_STATIC \
#undef static \
static \
#define static extern
The only thing I can think of is to leave static alone and define a new symbol, something like HARNESS_ACCESSIBLE.
#ifdef UNIT_TEST
#define HARNESS_ACCESSIBLE extern
#else
#define HARNESS_ACCESSIBLE static
#endif
But that is going to clutter up the production code with this new weird thing "HARNESS_ACCESSIBLE". Static variables within functions are generally rare, but almost all static functions (except trivial helper functions) will need to be externally accessible by my test runner.
I've been trying to avoid writing a separate script that has to run before builds, but I am getting to that point now.
I think your idea of creating a HARNESS_ACCESSIBLE macro is the cleanest way of going about this. You definitely don't want to be #define-ing away static for just the reasons you described.
I don't think using this macro will be cluttering up your code. You'll just be putting this in place of static, and it gives you the option of specifying exactly which functions you want to be able to unit test and keeping those minor utility functions explicitly static.
I want to encapsulate global variables in a single "data-manager-module".
Access is only possible with functions to avoid all the ugly
global variable problems ... So the content is completely hidden from the users.
Are there any existing concepts? How could such an implementation
look like? How should the values stored in the "data-manager-module"?
A "data manager module" doesn't make any sense. Implementing one would merely be sweeping away a fundamentally poor program design underneath the carpet, hiding it instead of actually cleaning it up. The main problem with globals is not user-abuse, but that they create tight couplings between modules in your project, making it hard to read and maintain, and also increases the chance of bugs "escalating" outside the module where the bug was located.
Every datum in your program belongs to a certain module, where a "module" consists of a h file and a corresponding c file. Call it module or class or ADT or whatever you like. Common sense and OO design both dictate that the variables need to be declared in the module where they actually belong, period.
You can either do so by declaring the variable at file scope static and then implement setter/getter functions. This is "poor man's private encapsulation" and not thread-safe, but for embedded systems it will work just fine in most cases. This is the embedded industry de facto standard of declaring such variables.
Or alternatively and more advanced, you can do true private encapsulation by declaring a struct as incomplete type in a h file, and define it in the C file. This is sometimes called "opaque type" and gives true encapsulation on object basis, meaning that you can declare multiple instances of the class. Opaque type can also be used to implement inheritance (though in rather burdensome ways).
Declare and define all the variables in a header file that is included into the manager's .c file but not into its .h
That way they will be only visible for the manager's functions.
You can keep all variables in a single source inside a struct with getters and setters
static struct all_globals{
long long myll;
/* ... */
} all_globals; /* Not _really_ global*/
long long getmyll(void){
return all_globals.myll;
}
long long setmyll(long long value){
return all_globals.myll = value;
}
similarly, you could use an internal header file that is not exported to the user API, then strip symbols from the resulting binary/library
/* globals.c */
struct all_globals{
long long myll;
/* ... */
} all_globals; /* Not _really_ global*/
/* globals.h */
#define getmyll() all_globals.myll
#define setmyll(value) all_globals.myll = (value)
This will still be technically visible to the end user with enough effort, but allows you to distinguish globals and keep them together.
Is it possible to block access to variables and functions as you would by having a separate file but in the same file? Like how in javascript you would use anonymous functions.
You can have hiding in the sense that the declaration of the static function or static variable can follow after the function it is hiding from. Using a macro, you can hack your way into hiding a function or variable after it has been defined.
static void foo () { /* ... */ }
static int g_hidden_from_foo;
static void bar () { /* can use foo() */ }
#define foo foo_is_now_private
/* effectively hides foo */
This may satisfy your curiosity, but I can't say it is convenient (or wise).
If you are open to using compiler extensions, GCC has nested functions, which is more or less similar to anonymous functions.
This is not directly possible in C. The unit of code in C is the translation unit, which is the fancy way of saying the file you're editing (plus header files).
Any code in a particular translation unit can "see" any of the preceding declarations and definitions. There is no way to change that in standard C. You can use macros or naming tricks to hide identifiers, but you can't outright stop access, especially not in a readable/convenient way.
If you're willing to use separate files you can simply avoid putting a declaration in your public header file to make the data "hidden" and can make function declarations as static to make them completely inaccessible to other translation units.
If you use C++ instead then you can get a bit further by using classes with protected and private members, as C++ protection semantics are per-class rather than per-translation-unit.
I'm making a little game in C. I try to program in an object-oriented manner using function pointers.
I really wanted to push ahead this time and not overdo making things too generic, I often get lost in this. Using plain old C has helped me a lot in programming faster and better.
Currently, I describe "Game states" using:
/* macros */
#define SETUP_ROUTINE(component) component##_##setup_routine
#define DRAW_ROUTINE(component) component##_##draw_routine
#define EVENT_ROUTINE(component) component##_##event_routine
#define UPDATE_ROUTINE(component) component##_##update_routine
#define TEARDOWN_ROUTINE(component) component##_##teardown_routine
#define SETUP_ROUTINE_SIGNATURE void
#define DRAW_ROUTINE_SIGNATURE void
#define EVENT_ROUTINE_SIGNATURE SDL_Event evt, int * quit
#define UPDATE_ROUTINE_SIGNATURE double t, float dt
#define TEARDOWN_ROUTINE_SIGNATURE void
/* data */
typedef enum GameStateType {
GAME_STATE_MENU,
GAME_STATE_LEVELSELECT,
...
} GameStateType;
typedef struct GameState {
GameStateType state;
GameStateType nextState;
GameStateType prevState;
void (*setup_routine)(SETUP_ROUTINE_SIGNATURE);
void (*draw_routine)(DRAW_ROUTINE_SIGNATURE);
void (*event_routine)(EVENT_ROUTINE_SIGNATURE);
void (*update_routine)(UPDATE_ROUTINE_SIGNATURE);
void (*teardown_routine)(TEARDOWN_ROUTINE_SIGNATURE);
} GameState;
While you may or may not appreciate this style, I have grown to like it and it serves me well so far on this small (private..) project.
I for instance have a "transition" game state that simply transitions from one game state to the other.
However, when I link the different game states together, I get ugly things like:
extern GameState GAME; /* The 'singleton' "game" */
extern void menu_setup_routine(SETUP_ROUTINE_SIGNATURE);
extern void menu_draw_routine(DRAW_ROUTINE_SIGNATURE);
extern void menu_event_routine(EVENT_ROUTINE_SIGNATURE);
extern void menu_update_routine(UPDATE_ROUTINE_SIGNATURE);
extern void menu_teardown_routine(TEARDOWN_ROUTINE_SIGNATURE);
extern void debug_setup_routine(SETUP_ROUTINE_SIGNATURE);
extern void debug_draw_routine(DRAW_ROUTINE_SIGNATURE);
extern void debug_event_routine(EVENT_ROUTINE_SIGNATURE);
extern void debug_update_routine(UPDATE_ROUTINE_SIGNATURE);
extern void debug_teardown_routine(TEARDOWN_ROUTINE_SIGNATURE);
Also, for each game state I have things like:
menu.c
struct MenuModel menu_model; /* The singleton 'menu' model */
game.c
struct GameModel game_model; /* The singleton 'game' model */
..which are global pieces of data that remain on the heap throughout the execution of the program. Of course the fields of these usually consist of pointers to dynamic memory, which and which contents' change as the game states change.
While at first I thought this was insane I started to like it. However it may cause namespace conflicts when another .o is linked that also has such a "menu_model" symbol.
First question: is this insane, is there a better way of doing things like this? What do people usually do to avoid these possible symbol name conflicts?
Second question is that I have to republish the different ..._setup_routine/..draw_routine/.. functions using "extern.." in the one source file/object file that holds the following types of functions:
void (*get_setup_routine(GameStateType state))(SETUP_ROUTINE_SIGNATURE) {
switch(state) {
case GAME_STATE_MENU:
return SETUP_ROUTINE(menu);
break;
case GAME_STATE_LEVELSELECT:
return SETUP_ROUTINE(level_select);
break;
default: /* ... */ break;
}
}
Because otherwise when compiling it does not know the symbol "menu_setup_routine".
Anyway, any advise is welcome, I'm a bit new to C and although I really like programming in it, I wonder if I'm using it right in this case.
Some non-small games use similar paradigm. The first example which pops into my mind is Neverball.
You might want to download its source code (its an OpenSource game) and see how they're doing.
Personally I think you should check C++. I used to use C only, also in the way you're doing, up to a some years ago; then I went crazy (mostly because of name clashes), and switching to C++ made me discover a new world. Anyway I understand you could want to avoid it for a number of reasons.
About objecst like your menu_model, whose name clashes with other menu_model in other C source files, you should just declare them as static:
static struct MenuModel menu_model; /* The singleton 'menu' model */
That menu_model will be visible in the C source file it's declared in (you won't be able to use it in other C source files, not even by externing it), and its name won't clash with other static variables with the same name declared in other C source files.
About the second issue there's not much to do. Functions and variables you use must be declared.
I'm a bit confused, but I don't think you should need all those menu_setup_routine and so on to have external linkage. Instead, define a struct game_vtable containing one function pointer for each routine, and then let each of "menu" and "debug" provide access to an instance of that struct. To call a function on a component, you do something like:
// vtable is a global symbol
component##_##vtable.setup
or
// vtable is acquired from a function
component##_##getvtableptr()->setup
or you can pass vtable pointers around as parameters, in place of your GameStateType, and maybe thereby get rid of some of your switch statements.
As for the globals - you don't provide a lot of detail, but the way to avoid a global Menu is to create one locally, at a high level, and then pass it around to anyone that needs it. If you decide that you prefer the global, you have to give it a unique name if it's going to be visible outside its TU.