6

I use #pragma once often and it seems to work fine when dealing with headers and but for some reason, the following creates the linker error of multiple definitions:

#pragma once
int someVariable=5;

Shouldn't the pragma prevent this too?

johnbakers
  • 24,158
  • 24
  • 130
  • 258
  • 2
    #pragma once is used in a header. don't define a variable in the header! just declare it. #pragma once only prevents it from being included multiple times by THE SAME file, but not multiple times total (e.g. can be included twice by two different files). – thang Jan 20 '13 at 08:30
  • 4
    It avoids the contents of the header to be included in same TU not across TU's. You are breaking the ODR by defining variable in header. – Alok Save Jan 20 '13 at 08:30

1 Answers1

7

Shouldn't the pragma prevent this too?

No, in this case multiple definitions of someVariable will be created if this header file is included in multiple places. If B.h and C.h both include your head file, then two someVariable will be created.

Better way is to define variables in only one .cpp file and use extern in other places.

billz
  • 44,644
  • 9
  • 83
  • 100
  • 3
    This is slightly misleading; if B.h and C.h, were in the same translation unit, you'd still only get one copy of the original header file. The problem is when 2 cop files include it and both have it in their object files. – Alex Chamberlain Jan 20 '13 at 09:29