multiple definition of variables in global.h

I have some variables which are used in different source files. so I create a global.h and put all variables in the header file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

using namespace std;

#ifndef __GLOBAL_H
#define __GLOBAL_H

#include<event.h>

#define RELAY_PORT 8000
#define ETHERNET_HDR_LEN 14

char local_ip[20];
struct event_base *base;

#endif 


when I build the project, I get the error of "multiple definition " of these variables.

what is wrong in my design?

thanks
Last edited on
Global variables are bad:
http://c2.com/cgi/wiki?GlobalVariablesAreBad
http://programmers.stackexchange.com/a/148109/89201
http://stackoverflow.com/a/485020/1959975
http://stackoverflow.com/a/10525602/1959975
(and many more via Google search)

Don't use global variables.

To answer your question though, you should declare the variables in your header and only define them in a single source file.
And you should never use the using statement in a header file. Also consider using const defined variables rather than the #define.
ah, OK, thank you

I define them in main.cpp, and use "extern" in global.h
in my main.cpp, there are several functions
1
2
3
4
5
6
7
8
9
10
11
func1(){
    ....
    some_func(base, arg2);
    ...
}

main(){
   .....
    struct event_base *base;
    .....
}


then it prompts error saying that the "base" is not defined in func1.
so I'm puzzled. if the function which uses base is above main() in the same file main.cpp ( main() is where the variable is defiend), then the variable is not defined. then why functions in separate files could use the variable?

BTW, if I should not use global variables, then what should I do?
Last edited on
if I should not use global variables, then what should I do?

Make the variables local to a function then pass to other functions as parameters returning values as required.
Topic archived. No new replies allowed.