MacOS – Different programs in the same Xcode C++ project

developmentmacossoftware-recommendationxcode

I am trying to use XCode as my training environment for simple C++ programs. If I create a new project, I can successfully complete everything (compile, run) but If I add one more file, it can't compile as a separate one. That means that I need to have a main2() and a main3() etc. because having 2 files with two main() in the same folder lead to an error.

In simple words, I want to write code for 30 C++ examples, each one in its own .cpp file and compile every one of them separately and not as a whole project (all files together that If there are two functions of the same name, it will crash).

Best Answer

In order to compile multiple separate files (separate binaries as a result) You would need to create separate targets for every file.

To add new target please choose: File -> New -> Target.., select for example Command Line Tool. Make sure it's properly added to Your project. Here's example: enter image description here

My main.cpp is added to target multiple_targets like this: enter image description here

My main-kopia.cpp file is added to target2 like this: enter image description here

to be sure check the build phases for every target, here's example of my target2 Build Phase: enter image description here

With this I am able to compile both main.cpp and main-kopia.cpp. Notice that they both have main() inside them.