简体   繁体   中英

Const declaration causing linker error in Xcode

I'm creating an openGL engine (one side for ES 1.1 and one for ES 2.0). Both of the engines currently have some constant Vertex's in them (as shown below). Unfortunately, when compiling I receive the following error:

 ld: 1 duplicate symbol for architecture i386
 clang: error: linker command failed with exit code 1 (use -v to see invocation) with the duplicate symbol being _Verticies. 

Why is Xcode complaining about a duplicated constant value in two separate files? The files to conform to the same protocol... but for the most part that's their connection. In C++, this method works fine, but causes the noted error when translated over to Objective-C.

//Define the positions and colors of two triangles
const Vertex Verticies[] = { //per vertex data
    {{-0.5f, -0.866f},{1.0f, 1.0f, 0.5f, 1.0f}},
    {{0.5f, -0.866f},{1.0f, 1.0f, 0.5f, 1.0f}},
    {{0.0f, 1.0f},{1.0f, 1.0f, 0.5f, 1.0f}},
    {{-0.5f, -0.866f},{0.5f, 0.5f, 0.5f, 0.0f}},
    {{0.5f, -0.866f},{0.5f, 0.5f, 0.5f}},
    {{0.0f, -0.4f},{0.5f, 0.5f, 0.5f}},
};

Solution: As of now it seems that by default const values in Objective-C are subjected to the project's scope rather just the file's scope. In C++, when creating a const value, the scope is automatically limited to the file it's in. To fix this problem in Objective-C, the static tag must be used to limit the scope to that particular file. You may also use an extern tag (but that would be a bit more work).

It works in C++ because in C++, a global variable with const is also implied to be static . This is not the case in C. When you change to Objective-C, which "inherits" from C, this behavior is lost and const symbols suddenly become extern .

Prefix your const variables with static to get the same behavior you had in C++.

If the Verticies variable is used in only one compilation unit (file) you should declare it using the storage class specifier static .

This prevents the compiler from emitting an external symbol visible to the linker. In C lingo: The symbol then has internal linkage.

One of the many subtle differences between C and C++ is that const in C does not imply internal linkage.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM