duplicate symbol error C++

后端 未结 4 2129
感情败类
感情败类 2020-11-29 06:35

I have added some const character in my file as under. The error i get is duplicate symbol _xyz(say). What is the problem with it and how could i get out of this.



        
4条回答
  •  猫巷女王i
    2020-11-29 06:57

    If this is in a header file, you're defining xyz every time you #include it.

    You can change the declaration as @R Samuel Klatchko shows. The usual way (if the data isn't const) is like this:

    In Abc.h:

    extern char *xyz;
    

    In Abc.cpp:

    char *xyz = "xyz";
    

    Edited to add

    Note that header guards will not solve this problem:

    #ifndef XYZ_H
    #define XYZ_H
    ...
    #endif
    

    Header guards prevent "redefinition" errors, where the same symbol appears twice in the same compilation unit. That's a compiler error.

    But even with header guards the definition of xyz will still appear in every source file that includes it, causing a "duplicate symbol" error, which is a linker error.

    It would have been more helpful if the original poster had mentioned that, of course.

提交回复
热议问题