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++.
Related
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 recently came across the C function with return type as void and package keyword added in front of it.
Could anyone please tell me what the meaning of package in the below mentioned C function prototype represents?
package void function (void)
The macro definition for the package:
/* function and variable scope modifiers */
#define package //accessible within package only,used for functions only
package is not a keyword in any C standard.
Perhaps it's being #defined by some header file you're not showing us.
Edit: package is being defined to nothing, so it has exactly zero effect in your program. Maybe if you told us what this header file was, and what this other code is you're trying to use, we might understand why it exists.
Sometimes the information you want to communicate to the reader in a declaration differs from the information that C lets you communicate.
For example, C's use of the static keyword can be confusing. On an object declaration at block scope, it affects the storage duration of the object; on an object declaration at file scope (outside any function body), it affects the linkage.
Programmers will sometimes try to extend the language, by defining macros that more clearly express the intent.
For example, I might write:
#define PUBLIC extern
#define PRIVATE static
PUBLIC void func1(void);
PRIVATE void func2(void);
As far as the compiler is concerned, this is exactly equivalent to:
extern void func1(void);
static void func2(void);
but it might be clearer to a human reader who happens to know, or can guess, what the PUBLIC and PRIVATE macros are supposed to mean.
In your case, you have:
#define package //accessible within package only,used for functions only
so package is replaced by nothing. (IMHO it would have been better to define PACKAGE, so it's obvious to a reader that this is a macro), followed by:
package void function (void);
The word package is ignored by the compiler. It's intended to convey to the human reader that the function function is intended to be "accessible within package only" -- whatever that means.
The C language does not have the concept of a "package". The largest unit of organization for a C program is the translation unit, consisting of a source file along with anything it #includes, directly or indirectly.
The author of the code presumably had something in mind as the definition of a "package". Perhaps it's some well-defined collection of translation units -- in which case there is no C syntax to express the restriction that the author intends.
One problem with this kind of thing is that although package looks like it could be a keyword, it's not enforced by the compiler. Perhaps there's another tool that checks the source files for "correct" use of package -- or perhaps it's entirely up to the maintainers of the code to use it correctly.
Without knowing what a "package" is, it's impossible to be sure what the package pseudo-keyword is supposed to mean. I hope that the term is precisely documented somewhere.
It can be a way for the author (programmer) to give the reader (maintenance programmer) some extra information about intentions and structure. From the comment "accessible within package only,used for functions only" it could also be defined as:
#define package static
Now all functions with "package" will be declared as static and have scope only within the "package" (source module/file). I see many programmers do things like this. Of course there is no standard for it so every time I have to find it out again "what's he doing?"
For example, in a program, I have a function that is used internally by other functions. But I want to restrict the use of this helping function in main(). Like private in C++.
You make the function static in your C file (which I assume is not the same C file as the one that has main()) and omit it in your header. Then it won't be callable from outside its own C file.
Define and use it in a separate compilation unit or #undef it at the end of your header if you must use it there. Are you sure you want a macro for what you're doing?
You can use #if and #endif for certain functions and declare them under a specific condition in the header file. The following example might help:
#if SPECIFIC_CONDITION
void functionOne();
BOOL functionTwo();
int functionThree();
#endif
void functionFour();
Thus all functions except functionFour() will act as private as you can call the top three functions under a specific condition only
Well, you put that function as private member of some struct or class so that you alone may use it and nobody else.
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.
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.