Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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).

like image 908
TheCodingArt Avatar asked Feb 20 '26 21:02

TheCodingArt


1 Answers

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++.

like image 142
zneak Avatar answered Feb 22 '26 12:02

zneak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!