Duplicate Symbols only when building for simlator

2019-06-17 06:42发布

When building for a device (ipad 3) my build works find with no warnings or errors, but when building for the iPad or iPhone simulator I receive linker errors like the following:

duplicate symbol _CONSTANT_NAME in:
/Users/me/libLibrary.a(FileName.o)
/Users/me/libOtherLibrary.a(OtherFileName.o)

The constants are defined like so in header files

const int CONSTANT_NAME = 123;

I have tried wrapping the constant's in #define tag's like so:

#ifndef CONSTANTS_H
#define CONSTANTS_H

const int CONSTANT_NAME = 123;

#endif

why does this work fine when building for device but cause issues when building for simulator?

1条回答
We Are One
2楼-- · 2019-06-17 07:14

The compiler is telling you exactly the correct thing. You are lucky that it's not happening when building to your iPad directly.

In every .m file where you include this header, you create a new and distinct variable with the same name. The compiler can resolve this when linking all these files into a single .a, but when multiple .a files are built and those multiple .a files are linked together, the compiler compiles about duplicate copies.

I would do one of three things:

  1. Turn the const int into a #define. #define CONSTANT_NAME 123
  2. Add static before const int. static const int CONSTANT_NAME = 123;
  3. Add extern before const int and add the real const int to a single .m. In .h, extern const int CONSTANT_NAME;. In the single .m, const int CONSTANT_NAME = 123;.

For the last one, I would create a constants.m file as a separate place to hold the const int CONSTANT_NAME = 123; definition.

Hope that helps.

查看更多
登录 后发表回答