0

I am using some constants defined in

Constanst.h

#ifndef __CONSTANTS_H__
#define __CONSTANTS_H__ 

namespace A{
    namespace B{

    const int FIRST = 1;
    const int SECOND = 2;
    }
}
#endif

I am including this file from 2 different .cpp (A.cpp and B.cpp)

gcc version 3.2.3 is giving me "multiple definition" linking errors

I solve the problem only by including another "File.h" which includes "Constants.h" and declares the same constants as "extern"

Can someone explain why? I supposed this was an issue in C, not C++

  • 1
    add header guards or #pragma once – Sugar Sep 27 '16 at 11:59
  • @Sugar I think that wouldn't help. – Danh Sep 27 '16 at 12:00
  • Of what type are these constants? If you are declaring variables in a header file, they will be instantiated in each compilation unit that includes that header. There are a number of ways around this, but usually when people _declare_ the variables (constant or not) in a header, they _define_ them in a .c file. Your `extern` just promises the compiler that the variables are defined elsewhere, and the linker will expect to find them somewhere among the compiled objects. – Josh Sanford Sep 27 '16 at 12:01
  • @CoryKramer Are you sure? `const` variables should have internal linkage per [this](http://stackoverflow.com/a/2328715/4342498) – NathanOliver Sep 27 '16 at 12:01
  • @Danh. This is C++ not C, C does not have namespaces? C++ with undeclared types called FIRST and SECOND :) – lfgtm Sep 27 '16 at 12:03
  • @Danh if it is linker error then absence of any include guards exactly an issue. absence of type for variable should be compile-time error i think – Sugar Sep 27 '16 at 12:04
  • @lfgtm that's the point. This code isn't valid for both C and C++ – Danh Sep 27 '16 at 12:04
  • @NathanOliver Good catch, I didn't realize that distinction existed. TIL – Cory Kramer Sep 27 '16 at 12:05
  • @Danh. True, upon further inspection it is neither. o.0 – lfgtm Sep 27 '16 at 12:07
  • @CoryKramer No problem. Thanks for reopening. – NathanOliver Sep 27 '16 at 12:23

1 Answers1

0

With g++ version 4.3.4:

constants.h:5: error: ISO C++ forbids declaration of `FIRST' with no type

after adding type int, it works.

So maybe you should use a newer compiler? Use g++ instead of gcc?

Rene
  • 2,466
  • 1
  • 12
  • 18
  • The files are A.cpp and B.cpp, shouldn't it be the same using gcc or g++? – ellysisland Sep 27 '16 at 12:44
  • Maybe not: http://stackoverflow.com/questions/172587/what-is-the-difference-between-g-and-gcc. Anyway: Please try with a newer version! – Rene Sep 27 '16 at 12:51
  • sorry I use g++, but the machine is old RHEL 3, so I can't change compiler version, anyway I see the issue may depend on the compiler version – ellysisland Sep 27 '16 at 13:26