0

I know this is answered before, but i could not resolve my issue even after applying lots of solutions available on stackoverflow. I have 2 source files main.cpp and util.cpp. and one header file main.hpp

#ifndef MAIN_HPP
#define MAIN_HPP

#include <iostream>

int driver = 0;
#endif

i am planning to use the driver variable in both files. and i do have a cmake file:

SET(Main_INCLUDE_DIR include)
SET(Main_SRC_DIR src)

INCLUDE_DIRECTORIES(${INCLUDE_DIRS}
${Main_INCLUDE_DIR}
)
ADD_EXECUTABLE(poc 
${Main_SRC_DIR}/main.cpp
    ${Main_SRC_DIR}/util.cpp 
    ${moc_srcs}

)

error:

CMakeFiles/src/util.cpp.o:(.bss+0x0): multiple definition of `driver'
CMakeFiles/src/main.cpp.o:(.bss+0x0): first defined here
cigien
  • 57,834
  • 11
  • 73
  • 112
geek
  • 794
  • 3
  • 16
  • 41
  • 3
    The header file should have a **declaration**, e.g. `extern int driver;`. The corresponding source file `main.cpp` should have the **definition**, e.g. `int driver = 0;`. – user3386109 Dec 17 '20 at 03:59
  • Thank you. if i want to retain the value? for example in main.cpp i run a function and update the value, and i want the value in util.cpp will driver have the last updated value? – geek Dec 17 '20 at 04:09
  • 2
    There's only one variable (not multiple variables with the same name) so that will just work. The declaration just says "there is such a variable" but does not actually create that variable. It's the definition that creates the variable. – kaylum Dec 17 '20 at 04:21

0 Answers0