Multiple definition of token - c

Given the following code,
button.h
#ifndef BUTTON_H_
#define BUTTON_H_
#define true 1
#define false 0
#include <avr/io.h>
#include <avr/interrupt.h>
#include <timer0.h>
typedef struct {
unsigned char port;
unsigned char pin;
unsigned long timestamp;
} BUTTONS;
BUTTONS button_1;
BUTTONS button_2;
BUTTONS button_3;
enum BUTTONS_ID{BUTTONS_ID_1,BUTTONS_ID_2,BUTTONS_ID_3,BUTTONS_ID_COUNT};
BUTTONS* button[BUTTONS_ID_COUNT] = {&button_1,&button_2,&button_3};
void Button_init(void);
#endif //BUTTON_H_
and button.c
#include <button.h>
enum BUTTONS_state{BUTTON_STATE_UNPRESSED,BUTTON_STATE_DEBOUNCING,BUTTON_STATE_PRESSED};
int state = BUTTON_STATE_UNPRESSED;
void Button_init(void){
button[BUTTONS_ID_1]->port = PINB;
button[BUTTONS_ID_1]->pin = PINB4;
button[BUTTONS_ID_1]->timestamp = 0;
}
I get the following error : button.cpp : multiple definition of `button_1'. I know I must be doing something wrong. I am quite new at using structure the mistake must be coming from there. Basically I wanted to create button variable which I could access from my main program if need be. Is there a way to define them in my .h and initialize them within my .c and then access them from my main file?
Thank you

You've defined button1 and several other objects in your header file. If you include this header in multiple translation units (read: source files), you'll end up with one definition for each translation unit you compile. Then later, when you try to link -> KABOOM.
The simple solution is "don't put code that defines objects in your header." If you need to access them in multiple source files, you can leave the declarations, but you'll need to mark them extern. Then you can make the definition in a source file elsewhere.

You should not declare variables in header files. This is because when a header file is #included in a c file it is literally copied to it by the preprocessor.
So if 2 c files include the same h file, which in turn declares a variable, you end up with the same variable declared twice in both files. That's probably what happened here - you probably #included button.h in another c file.
The best way to make a variable application global is to declare it in only one file, and then declare it using extern in each c file where you want to use it.
In your example, do
BUTTONS button_1;
BUTTONS button_2;
BUTTONS button_3;
in one c file, and in all other c files where you want to use these vars, do:
extern BUTTONS button_1;
extern BUTTONS button_2;
extern BUTTONS button_3;
There is also other ways to do it. It's possible to use some preprocessor acrobatics and declare you variables in a header file in such a way that only in one file there are declared as global variables, and in all other files they are declared with extern. But personally I don't like this, because I do think that variables declaration do not belong in header files.
Besides, it's best to try not to use application global variables, which leads to ways of doing modular programming, low coupling and all that stuff. It's a very interesting and important topic, but is to wide for this answer.. :-)

Related

Where can I declare global variable in c program , whether in header or source file [duplicate]

This question already has answers here:
How do I use extern to share variables between source files?
(19 answers)
Closed 6 years ago.
Hi I am a C++ developer now I am doing C programming.
My question is which place is better to declare global variable in c program.
Header or source file (provided my global variable is not used in other files)?
I want that variable like private variable in C++.
Assuming your variable is global and non static.
You need to declare it in a header file. We use extern keyword for this. As pointed out in comments, this keywords is not necessary, but most C users prefer to use it in headers, this is a convention.
stackoverflow.h:
#ifndef STACHOVERFLOW_H
#define STACHOVERFLOW_H
extern int my_var;
#ifndef
And you initialize it in source file. (Use of keyword extern is prohibited if you want to provide an initialization value).
stackoverflow.c
#include "stackoverflow.h"
int my_var = 50;
Do not put initialization value in a header, or you will get a linker error if the header is used at least twice.
Now you can use your variable in any other module by including the header.
main.c
#include <stdio.h>
#include "stackoverflow.h"
int main()
{
printf("my_var = %d\n", my_var);
return 0;
}
Including header "stackoverflow.h" in "stackoverflow.c" is a way to get sure definitions in source file match declarations in header file. This permit to have errors as soon as compilation instead of sometimes cryptic linker errors.
Edit: This is not at all the way to make a variable "private". You have to use a static variable to make it "private". See R Sahu's answer
which place is better to declare a global variable in c program
Answer: In source(*.c) file.
Assume the scenario like, I have declared a variable in a header file. I included this header in two different .c files. After the macro expansion step of compilation, these two files will have the global variable with the same name. So it will throw an error like multiple declarations of the variable during the linking time.
Conclusion:-
Keep all global variable declaration on .c file and put it as static if it is doesn't need in other files.
Add extern declaration of the variable in the corresponding header file if it's needed to access from other files
You should not place global non-constant variables anywhere. Global as in declared with extern and available to your whole project. The need to do this always originates from bad program design, period. This is true for C and C++ both.
The exception is const variables, which are perfectly fine to share across multiple files.
In the case you need file scope variables, they should be declared in the .c file and always as static. Don't confuse these for "globals" because they are local to the translation unit where they are declared. More info about how static file scope variables can make sense.
Also note the C standard future language directions:
Declaring an identifier with internal linkage at file scope without
the static storage class specifier is an obsolescent feature.
So if you don't use static your code might not compile in the next version of the C standard.
If you intend to use the global variables in multiple .c files, it is better to declare them in .h files. However, if you want to keep the variables like private member data of classes in C++, it will be better to provide access to the global data through functions.
Instead of
extern int foo;
Use
int getFoo();
void setFoo(int);
That sort of mimics the private access specifiers for member variables of classes.
Generally what you can do is define the variable in a source file, like int g_foo;, then reference this global in other files with extern, like extern int g_foo; do_sth(g_foo);. You could put the extern int g_foo; declaration in a header file, and include that in other source files. It's not recommend to have definitions of data in header files.
If you want it to be global (external linkage), you should put it in .h file. And this is one of the best practise, I think:
public_header.h
#ifdef YOUR_SOURCE
#define EXTERN
#else
#define EXTERN extern
#endif
EXTERN int global_var;
your_source.c
//your source makes definition for global_var
#define YOUR_SOURCE
#include <public_header.h>
other_source.c
#include <public_header.h> //other sources make declaration for global_var
If you want it to be private (internal linkage), the best solution, I think, is just make definition of it right in your source file instead of header file to prevent the header file is included by another source and then make confuse.
your_souce.c
static int private_var;

C - Including variable (struct) declarations and functions in separate files

I am working on a C project in which part of the code is generated by a different application. The separate files would contain the following:
Type definitions, main(), and other functions
Variable declarations (whose type definition is in the file above) and functions to work with those variables
As mentioned, the information in the second file is generated by a different program, but it uses the type declarations in the main file. Similarly, the main program uses the variables and functions defined in the second file.
I have tried using the "include" and "extern" statements but have not been very successful at it. Since the two files are getting information from each other, would it be more useful to break them up in three files as follows?
1) Type definitions
2) Variable declarations (using the types defined in file 1) and related functions
3) Main() and the rest of functions that use the two above files
If this was the way to go, how would it work? Would it use include or extern, and how would I need to use these clauses?
Any help you can provide is greatly appreciated. Thank you!
There is nothing wrong with the layout you are suggesting. Perhaps some clarification on what extern and #include do would be helpful.
1) #include is a preprocessor directive which essentially says: `take the named file and pretend it is pasted in place of this directive'
2) extern is a C reserved word. Not to get into too many technicalities, but its meaning is: `the variable named in this statement is defined in a different place'. The space for a variable is reserved by the compiler exactly once, so if a function needs access to the variable in question, some information is needed before the definition is seen by the compiler. An extern declaration has enough information for the function to use the variable and the linker makes sure that a correct variable is used at a later stage.
So in your scenario, the file with type definitions will be #include'd in every file that refers to those types. If you want to collect all the variable definitions in one file, which will be compiled separately from other parts of your project, any file that uses those variables and will be compiled separately, needs to be supplied an extern declaration for each variable defined elsewhere. Note that if you simply include th file with variable definitions, the compiler will see the definition twice (first in the file with the definitions, then in the file that includes it) and assume you are trying to define each variable twice and will issue an error.
Finally, here is a simple scenario (it does not really make sense and is in bad style):
a.c---------
#include "t.h"
mytype a;
mytype b;
int f( int x, int y ) {
return (x + y)*a - b;
}
m.c---------
#include <stdio.h> // for stdout
#include "t.h"
#include "v.h"
int main () {
fprintf( stdout, "%d", a + b - f(1, 2) );
return 0;
}
t.h-----------
typedef int mytype;
v.h-----------
#include "t.h"
extern mytype a, b;
int f( int, int );
v.h and t.h can be combined (it is a question of style and the project requirements). Note that a declaration of f in v.h has an implied extern in front of it.
As outlined in a comment, you will almost certainly need a header — call it header.h — which will be included in both the file containing the main program (file 1, call it main.c) and in the generated file (file 2, call it generated.c).
The header file will contain the type definitions and shared function declarations (and, perish the thought, declarations for any global variables). It will be self-contained and idempotent (see, amongst others, the Stack Overflow questions What are extern variables in C?, Should I use #include in headers?, How to link multiple implementation files in C?, and Linking against a static library).
Both main.c and generated.c will include header.h. To ensure that header.h is self-contained, one (or both) of the files will #include "header.h" as the first header.
Finally fixed. If anybody else has the same problem, I followed Alexsh's steps but I also had to include guards in my .h files to prevent redefinitions (otherwise it wouldn't compile). Thank you very much to both Alexsh and Jonathan for their help!

What's the difference between using extern and #including header files?

I am beginning to question the usefulness of "extern" keyword which is used to access variables/functions in other modules(in other files). Aren't we doing the same thing when we are using #include preprocessor to import a header file with variables/functions prototypes or function/variables definitions?
extern is needed because it declares that the symbol exists and is of a certain type, and does not allocate storage for it.
If you do:
int foo;
In a header file that is shared between several source files, you will get a linker error because each source would have its own copy of foo created and the linker will be unable to resolve the symbol.
Instead, if you have:
extern int foo;
In the header, it would declare a symbol that is defined elsewhere in each source file.
One (and only one) source file would contain
int foo;
which creates a single instance of foo for the linker to resolve.
No. The #include is a preprocessor command that says "put all of the text from this other file right here". So, all of the functions and variables in the included file are defined in the current file.
The #include preprocessor directive simply copy/pastes the text of the included file into the current position in the current file.
extern marks that a variable or function exists externally to this source file. This is done by the originator ("I am making this data available externally"), and by the recipient ("I am marking that there is external data I need"). A recipient with an unsatisfied extern will cause an Undefined Symbol error.
Which to use? I prefer using #include with the include guard pattern:
#ifndef HEADER_NAME_H
#define HEADER_NAME_H
<write your header code here>
#endif
This pattern allows you to cleanly separate anything you want an outsider to have access to into the header, without worrying about a double-include error. Any time I have to open a .c file to find what externs are available, the lack of a clear interface makes my soul gem crack.
There are indeed two ways of using functions/variables across translation units (a translation unit is usually a *.c/*.cc file).
One is the forward declaration:
Declare functions/variables using extern in the calling file. extern is actually optional for functions (functions are automatically extern), but not for variables.
Implement the function/variables in the implementing file.
The other is using header files:
Declare functions/variables using extern in a header file (*.h/*.hh). Still, extern is optional for functions, but not for variables. So you don't normally see extern before functions in header files.
In the calling *.c/*.cc file, #include the header, and call the function/variable as needed.
In the implementing *.c/*.cc file, #include the header, and implement the function/variable.
Google C++ style guide has some good discussions on the pros and cons of the two approaches.
Personally, I would prefer the header file approach, as it is the single place (the header file) a function signature is defined, calling and implementation all adhere to this one piece of definition. Thus, there would be no unnecessary discrepancies that might occur in the forward declaration approach.

How do I share variables between different .c files? [duplicate]

This question already has answers here:
How do I use extern to share variables between source files?
(19 answers)
Closed 6 years ago.
beginner question about C declaration:
In a .c file, how to use variables defined in another .c file?
In fileA.c:
int myGlobal = 0;
In fileA.h
extern int myGlobal;
In fileB.c:
#include "fileA.h"
myGlobal = 1;
So this is how it works:
the variable lives in fileA.c
fileA.h tells the world that it exists, and what its type is (int)
fileB.c includes fileA.h so that the compiler knows about myGlobal before fileB.c tries to use it.
if the variable is :
int foo;
in the 2nd C file you declare:
extern int foo;
In 99.9% of all cases it is bad program design to share non-constant, global variables between files. There are very few cases when you actually need to do this: they are so rare that I cannot come up with any valid cases. Declarations of hardware registers perhaps.
In most of the cases, you should either use (possibly inlined) setter/getter functions ("public"), static variables at file scope ("private"), or incomplete type implementations ("private") instead.
In those few rare cases when you need to share a variable between files, do like this:
// file.h
extern int my_var;
// file.c
#include "file.h"
int my_var = something;
// main.c
#include "file.h"
use(my_var);
Never put any form of variable definition in a h-file.
Try to avoid globals. If you must use a global, see the other answers.
Pass it as an argument to a function.
Those other variables would have to be declared public (use extern, public is for C++), and you would have to include that .c file. However, I recommend creating appropriate .h files to define all of your variables.
For example, for hello.c, you would have a hello.h, and hello.h would store your variable definitions. Then another .c file, such as world.c would have this piece of code at the top:
#include "hello.h"
That will allow world.c to use variables that are defined in hello.h
It's slightly more complicated than that though. You may use < > to include library files found on your OS's path. As a beginner I would stick all of your files in the same folder and use the " " syntax.
The 2nd file needs to know about the existance of your variable. To do this you declare the variable again but use the keyword extern in front of it. This tells the compiler that the variable is available but declared somewhere else, thus prevent instanciating it (again, which would cause clashes when linking). While you can put the extern declaration in the C file itself it's common style to have an accompanying header (i.e. .h) file for each .c file that provides functions or variables to others which hold the extern declaration. This way you avoid copying the extern declaration, especially if it's used in multiple other files. The same applies for functions, though you don't need the keyword extern for them.
That way you would have at least three files: the source file that declares the variable, it's acompanying header that does the extern declaration and the second source file that #includes the header to gain access to the exported variable (or any other symbol exported in the header). Of course you need all source files (or the appropriate object files) when trying to link something like that, as the linker needs to resolve the symbol which is only possible if it actually exists in the files linked.

Keeping variables global to the library scope in C

Is there any way to keep global variables visible only from inside a library while inaccessible from programs that access that library in C?
It's not that it is vital to keep the variable protected, but I would rather it if programs couldn't import it as it is nothing of their business.
I don't care about solutions involving macros.
If you use g++, you can use the linker facilities for that using attributes.
__attribute__((visibility("hidden"))) int whatever;
You can also mark everything as hidden and mark explicitly what is visible with this flag: -fvisibility=hidden
And then mark the visible variables with:
__attribute__((visibility("default"))) int whatever;
static int somelocalvar = 0;
that makes somelocalvar visible only from whithin the source file where it is declared (reference and example).
Inside the library implementation, declare your variables like that:
struct my_lib_variables
{
int var1;
char var2;
};
Now in the header for end-users, declare it like that:
struct my_lib_variables;
It declares the structure as an incomplete type. People who will use the header will be able to create a pointer to the struct, but that's all. The goal is that they have to write something like that:
#include "my_lib.h"
struct my_lib_variables* p = my_lib_init();
my_lib_do_something(p);
my_lib_destroy(p);
The libray code is able to modify the variables, but the library can't do it directly.
Or you can use global variables, but put the extern declarations inside a header which will not be used by the end-user.
You can use another header file for exporting functionality to outside modules than you have for the internal functionality and thus you don't have to declare globals that doesn't have to be accessible from outside the module.
Edit:
There is only linker problems if you declare things more than once. There is no need to keep all global data in one header file, in fact, there may be a wise reason top split it up into several smaller pieces for maintainability and different areas of responisiblity. Splitting up into header files for external data and internal data is one such reason and this should not be a problem since it is possible to include more than one header file into the same source file. And don't forget the guards in the header files, this way, collision in linking is mostly avoided.
#ifndef XXX_HEADER_FILE
#define XXX_HEADER_FILE
code
#endif

Resources