0

I have a question about global variable in header file.

I learned that when using a preprocessor, the contents of the header are imported into the cpp file.

I think that when I write the code as below, the header file is called once and the global variable is declared once, so why does the LNK2005(multiple definition) error occur?

// main.c
#include "student.h"

int main() {
    cout << a << endl;
    return 0;
}
// student.h
#ifndef _STUDENT_H_
#define _STUDENT_H_
#include <iostream>
using namespace std;

int a = 33;

#else
#endif
// student.c
#include "student.h"

Using 'extern' solves the problem, but errors do not occur even if i declare it as a 'const'.

const int a=33;

Does the 'const' also have a function of sharing global variables?

I'm curious about the principle of internal function

user17732522
  • 53,019
  • 2
  • 56
  • 105
  • Because you have two translation units: The two `.c` files. Each of them will include the header file once. – user17732522 Jan 16 '22 at 16:44
  • Btw. your code is C++, not C. If you are writing C++ I suggest that you don't use the `.c` file ending. It may confuse IDEs and such. Typically source files in C++ have an ending like `.cpp`, `.cc`, `.cxx`, etc. – user17732522 Jan 16 '22 at 16:44
  • just watch this [youtube video](https://www.youtube.com/watch?v=cpkDQaYttR4&ab_channel=CppCon) , it details how the compiler and linker work. – Ahmed AEK Jan 16 '22 at 16:46
  • *Does the 'const' also have a function of sharing global variables?* In C++ const implicitly defaults to static at namespace level. – 273K Jan 16 '22 at 16:48

0 Answers0