C++ class redefinition error - Help me understand headers and linking

后端 未结 3 583
梦毁少年i
梦毁少年i 2021-01-12 13:54

I started writing a simple interpreter in C++ with a class structure that I will describe below, but I quit and rewrote the thing in Java because headers were giving me a ha

3条回答
  •  不要未来只要你来
    2021-01-12 14:19

    C/C++ compilation is divided in compilation/translation units to generate object files. (.o, .obj)

    see here the definition of translation unit

    An #include directive in a C/C++ file results in the direct equivalent of a simple recursive copy-paste in the same file. You can try it as an experiment.

    So if the same translation unit includes the same header twice the compiler sees that some entities are being defined multiple times, as it would happen if you write them in the same file. The error output would be exactly the same.

    There is no built-in protection in the language that prevents you to do multiple inclusions, so you have to resort to write the include guard or specific #pragma boilerplate for each C/C++ header.

提交回复
热议问题