Header guard / translation unit problem

后端 未结 2 1017
长发绾君心
长发绾君心 2021-01-14 23:51

I was under the impression that header guards solve the problem of redefinition. I\'m getting linker errors that say there are redefinitions in the .obj files. This is the h

2条回答
  •  臣服心动
    2021-01-15 00:36

    Header guards only prevent the guarded portion of the header file from being included twice. The result is passed to the compiler, so the compiler does not know anything of the header guards.

    Consequently it will emit these symbols for every translation unit that includes the header (since it can not know that there was somewhere another unrelated translation unit compiled).

    Also the linker can not know that you didn't wanted this to happen.

    To solve the problem, declare the variables extern in the header, and define them in one single translation unit.

提交回复
热议问题