If you are a regular reader of this blog you’ve probably noticed that I tend to use the command line to compile, test and execute my C++ code. I do this even when I code on operating systems without a strong command line usage culture like Windows. Yesterday I’ve received an email from Zsolt, one of my readers, asking if it is possible to create a C++11 project directly in Xcode. The answer was, obviously, yes! I think this topic could be of interest for more than one coder, so I’ve decided to write a short post about this.
Let’s start with something simple, like filling a vector with some values and printing the result on screen:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | //Demo program to test the new C++11 initializer lists
#include <iostream>
#include <vector>
using namespace std;
int main()
{
// Test initializer lists and range based for loop
vector<int> V({1,2,3});
cout << "V =" << endl;
for(auto e : V) {
cout << e << endl;
}
return 0;
}
|
Compiling the above code from the command line is trivial, assuming you have the Command Line Tools for Xcode 4.5 installed, just open a Terminal and write:
1 | clang++ -std=c++11 -stdlib=libc++ test.cpp -o test
|
where test.cpp is the name of the C++ source file, if you’ve used a different name change the above command accordingly. If you run the resulting executable, you should see the content of the vector V on the screen:
1 2 3 4 5 | ./test
V =
1
2
3
|
Now, let’s do the same thing in Xcode. Start Xcode and select Create a new Xcode project:
From the Chose a template for your new project panel select OS X -> Application -> Command Line Tool and press Next:
Next panel is Chose options for your project, at Product Name chose a name for the project, I’ve used Test. In the Organization Name and Company Identifier put something meaningful to you if these fields are empty. It is important that you select C++ at Type and deselect Use Automatic Reference Counting:
In the next panel you will select where on your computer the project will be saved, I’ve saved this on Desktop and press Create:
From the left panel select main.cpp, replace the C++ code from here with the code presented at the beginning of this post and press the Run button, you should see the result in the All output panel:
If you are interested in learning more about the new C++11 syntax I would recommend reading Professional C++ by M. Gregoire, N. A. Solter, S. J. Kleper 2nd edition:
or, if you are a C++ beginner you could read C++ Primer (5th Edition) by S. B. Lippman, J. Lajoie, B. E. Moo.




