c - Why can't I declare and assign global variable in a header file, even when using #ifndef HEADER_H -
i saw similar questions, in none of them, #ifndef header_h
mentioned.
i have header file , 2 c files: constants.h
main.c
mylib.c
in constants.h:
#ifndef constants_h #define constants_h const int num_of_items = 22; #endif
in mylib.c:
#include "constants.h" ... code ...
in main.c:
#include "constants.h" int main() { ... code ... }
when compile using command: gcc main.c mylib.c -o main
, next error:
/tmp/ccl55fv3.o:(.rodata+0x0): multiple definition of `num_of_items' /tmp/ccyzhu6f.o:(.rodata+0x0): first defined here collect2: ld returned 1 exit status
i mentioned #ifndef
, why happens?? is there except splitting constants.h
declaration , constants.c
assignment?
the include guard required prevent multiple-inclusion single translation unit during compilation. error have on other hand linker error - because have more 1 translation unit (object file) containing same definition.
in c 1 commonly utilize #define
define constants macros. has downsides respect type safety. alternatively can 1 2 things:
localise constant in each translation unit declaring static
:
static const int num_of_items = 22;
declare extern
, define in single translation unit:
extern const int num_of_items ;
constants.c:
#include constants .h const int num_of_items = 22;
option 1 mutual practice in c++ semantics of const
different c, or @ to the lowest degree more defined, , unless reference or pointer taken constant, constant inserted code if macro - i.e. there no distinct storage of "variable". in c code may or may not happen, work either way potentially marginally less efficiently.
c gcc
No comments:
Post a Comment