How to use extern for sharing variables between C++ files?
Hi! I started learning C++ and I'm trying to split my program into multiple files. I have three files: main.cpp, functions.cpp and functions.h. In functions.h I declared a global variable int global_counter = 0; and several functions. In functions.cpp I defined these functions that modify global_counter. In main.cpp I include functions.h and try to use global_counter, but the compiler gives an error "multiple definition of `global_counter`". I've heard something about the extern keyword, but I don't fully understand how to use it correctly. Can you explain with a simple example? Here's my current code:
// functions.h
#ifndef FUNCTIONS_H
#define FUNCTIONS_H
int global_counter = 0;
void increment();
void print_counter();
#endif
// functions.cpp
#include "functions.h"
#include
No answers yet.
Log in to leave an answer
Blogs