Odd C behavior: variable visible when it shouldn't be - c

In my program, I have a file called constants.h that declares the following matrix in a global scope (the matrix should be fully constant - if anyone sees a potential problem, let me know):
static unsigned char const MY_MATRIX[66][9] = {...};
In another file, let's call it main.c, I can actually reference this constant:
doSomething(var1, count, MY_MATRIX[42], TRUE, FALSE, thing);
But then I just read the definition of the keyword static and it's supposed to mean that the variable cannot be accessed outside the file it's defined in. (In this case, the desired behavior is that it should be accessed, but then it seems the extern keyword is the one to use!)
So, can anyone tell me why this works? Why is the variable not invisible? Thanks!

This is because you are declaring a static variable in a header: when you include the header in a C file, you get a brand-new definition independent of the other definitions. If you include the header in two files, you get two independent copies; if you include it in three C files, you get three independent copies, and so on. The copies do not conflict with each other, because the static definition hides them from the linker.
A proper way to make use of a shared piece of data allocated in a static memory is to make the declaration extern in the header, and then add a non-static definition in exactly one C file.

If it's in a header, it's defined in every single source file you include it in (though each source file will have their own instantiation of it - they don't access the same one).

There are two uses of the static keyword:
A static variable inside a function block keeps its value between subsequent calls.
A static global variable or a function is "visible" only in the file it has been declared in.
Here, you define the matrix in a header file, hence it is visible to all the .c files which include that header file. To restrict its visibility, define it in a .c file instead.

Usually when a static variable is declared in a header file its scope is not limited to .h file meaning nothing like header file scope. The translation unit includes the text from header file in source file. Therefore every translation unit including header file gets its own individual variable though it is static scope.

Related

Global variables in a header file

I was just wondering if you declare a variable in a header file like this
const static int START = 0;
would that variable (START) be considered global?
If you define:
const static int START = 0;
at file scope, then START will have internal linkage and static duration due to static.
This means that each translation unit that includes the header will end up with a copy of the symbol and that each of them will live throughout the entire program.
Yes and no.
Lets say you add that definition into 'myvar.h' and then you include that header file into 'main.c' and 'other.c'
All functions in 'main.c' and 'other.c' will know about the defined variable --so in a way, it is global.
But in fact there will be two different variables with the same name. Changes made by functions in 'main.c' won't be visible by functions in 'other.c' and vice versa.
That's because static variables defined outside of functions are considered 'local to the compilation unit'.
On the other hand, if you just remove the 'static' keyword, the variable will be defined twice (once for each compilation unit in which the header file is included) and the linker will emit a 'duplicate symbol' error.

Static const variable declaration in a header file

If I declare static const variable in header file like this:
static const int my_variable = 1;
and then include this header in more than one .c files, will compilator make new instance per each file or will be "smart" enough to see it is const and will make only one instance for all the files?
I know I can make it extern and define it in one of .c files that include this header but this is what I am trying not to do.
I answered this at length here. That answer is for C++, but it holds true for C as well.
The translation unit is the individual source file. Each translation unit including your header will "see" a static const int. The static, in this context, means the scope of my_variable is limited to the translation unit. So you end up with a separate my_variable for each translation unit (".c file").
The compiler would not be "smart" to create only one instance for all files, it would be faulty, because you explicitly told it not to do so (static).
If you use address of that object - compiler surely creates one instance per each translation unit. If you use only value - it is probably smart enough to avoid creating of object at all - value will be inlined where need.
I guess it will make only one instance for all files. But you can verify it by calling it in different files and check its value

Unused function warning

I have method in header file to which I added static keyword. e.g.
static int32_t Tlvlist_AddRawt(Tlvlist *a, uint8_t type, uint16_t size, const void *bytes);
The method is implemented in .c file where the static
keyword is not present in function name.
This method is called from another function of same .c file.
The later function (which uses this static function) is also called from main.
But I get warning: "Unused function 'Tlvlist_AddRawt'" in the header file.
Why would this happen?
ps. I use Xcode.
When you mark a function declaration static, it is not visible outside the translation unit in which it appears. But also, it represents a different function in every translation unit in which it appears. As such, it is rarely a good idea to use static in a header file, because then you're declaring a separate function in each C source that includes the header.
The compiler diagnostic is telling you that there is at least one C file that includes your header but does not provide a definition of Tlvlist_AddRawt() to go with the declaration from the header.
If you want to declare a static function separately from its definition -- for instance to prototype it for other functions that appear earlier in the source file -- then put the declaration in at the top of the C source file in which its body appears instead of in a header. Putting it in a header is counterproductive.
You never declare static functions in a header file intended for use in other modules, because the purpose behind making a function static is "hiding" it from users outside your modules. Static C functions are visible only inside the translation unit* where they are defined. When a function is declared static, but no other functions from the same translation unit use it, you get the "unused static" warning.
If you would like to define a function in one file, and use it from another file, you need to put its forward declaration in a header, include that header from both translation units, and link the translation results together. Removing the static keyword from the header should address this problem.
* Translation Unit is a fancy name for a .c file.

Static struct declaration and initialization in c header file

I develop an embedded application which uses the MindTree Bluetooth SDK.
I have the following in a header file:
typedef struct {
UCHAR outputDir;
UCHAR reset;
UCHAR nack;
UCHAR startCondition;
UCHAR stopCondition;
UCHAR busy;
} USCI_ConfigurationFlags;
static USCI_ConfigurationFlags usciConfigFlags = { UCTR, UCSWRST, UCNACKIFG, UCTXSTT, UCTXSTP, UCBBUSY };
Later in two .c files I include the above header and use the usciConfigFlags on different occasions sometimes from within an interrupt.
Is this legal?
I'm trying to understand why(and if it is related to the question) the values of the struct change at runtime, after calling the BT_bluetooth_on method in the SDK.
Thanks,
Adam.
static here doesn't mean what you think it means. It means that the declaration and variable will only be visible in one compilation unit. That is, you have two independent instances of usciConfigFlags.
If you want a global variable, you need to use extern not static and make the actual declaration (without extern) with the initial value in one of your c files.
Also be weary of changing the values in the struct without proper locking. Read-only concurrent access is usually fine.
There is no problem you include the header in two .c file. The static modifier limits the accessible scope of the variable in the file including the header only. The two usciConfigFlags in two different files are not identical.
Also static does not mean constant. So you can modify the value of the structure in whatever way you want.
The following is from wikipedia
In computer programming, a static variable is a variable that has been
allocated statically — whose lifetime extends across the entire run of
the program. This is in contrast to the more ephemeral automatic
variables (local variables), whose storage is allocated and
deallocated on the call stack; and in contrast to objects whose
storage is dynamically allocated.
Prepending a static keyword to a variable makes it visible only in the current translation unit (i.e. if within a function, only that function and if within a file, only that file).
It is never a good idea to define a variable in a header file. Even if you need two static variables in two different files with the same name, it is better that you put in the .c file itself as it helps in better maintaince and readability as you will be clear in which all files it is actually present and is being used.
If you add it in a header file, then at a later point, if some other .c file includes this header, then unneccessarily this variable will included for that translation unit.
Epsalon had suggested other good points which you can consider.

How to deal with duplicated function name within C?

I have a little project in which I named two same name function in two different source file, but while I building the project, the compiler failed with 'func_name already defined in filename.obj'.
Why could not I have two functions with the same name in two different source files? I thought the function should be local to the source file only if when we declared it in the header file will it become global.
And except for changing the filename, are there any other elegant solution to duplicated function name in the C programming language?
In C, a function has global scope by default. To restrict its scope, use the static keyword to make it private to a the module.
The role of the header file is just to publicize the function along with its signature to other modules.
All global names must (with some caveats) be unique. This makes sense because that name is what is used by the linker to connect a function call to implementation of the function itself.
Names with static and local scope need only be unique within their scope.
Whether some thing is declared in header file or in source file makes absolutely no difference for the compiler. In fact, the compiler proper knows absolutely nothing about any "header files", since header files are embedded into source files by so called preprocessor, which does its work before the compiler proper. By the time the source files (with embedded header files) get to the actual compiler, there's no way to tell what was there originally and what was inserted from header files. The source file with all the header files embedded into it is called translation unit. I.e. the compiler proper works with translation units, not with some "source" or "header" files.
In C language all objects and functions declared at file scope have external linkage by default, which means that they are global, unique for the entire program. So, you thought incorrectly. Functions are not local to one source file only.
If you want to make a function (or an object) local to a single translation unit, you have to take some explicit steps. You have to declare it as static. Declaring it as static will give it internal linkage, which essentially means that it becomes internal to its translation unit.
Declaring your functions static will only work if both of them really have to be local to their own translation units. If this is not the case, i.e. if at least one of the functions should be a globally accessible (linkable) function, then you have no other choice but to rename one of functions.
Why could not I have two function with the same name in two differenct source file?
Because the linker needs to know which is meant when you reference it.
Imagine that a.h and b.h both declare my_function(). The compiler generates code for both. Now, imagine that c.c calls my_function() - how does the linker know which of the two versions of the function should be called?
Declare the function static to make it local to the file. In C, every identifier name must be unique.
The elegant solution is namespaces introduced in C++. The solution, if there are few calls to func_name is take one, rename it and recompile.
Something hackerous but quick solution might be this:
//In one of the two source files and any file that calls it
//if your functions is something like this
//void func_name(int) { ... }
//Add the following line
#define func_name SOME_UNIQUE_FUNC_NAME

Resources