c++xcodetargets

Add multiple independent main() programs in one project - XCode


I've very big problems with XCode. First of all, I want to tell you that my starting language was Java. In Java you can write multiple programs in one project, which is very useful for smaller programs, f.e. Hello World.

Now I want to learn C++ and write some programs for exercise. I already wrote one in my project "Uebung" (= Exercise). Now I want to write another program, which is completely independent of my previous program, but it's still an exercise program, so I want it in my "Uebung" project.

I've researched and found out that targets are my solution. Unfortunately, I can't figure it out how to configure them properly.

You can see the build Phase of my program "NumberCounter". Look at the bottom right corner, there you'll see that it works:

Here

Now I want in my Project "Uebung" and in the Folder "Uebung" a new program with a main.

I go to File -> New -> Target -> Command Line Tool and choose a name for my new target.

Now a new folder pops out with the same name as my target. Note that the target is red and I don't know why. The Compile Source is the new main in the folder "test":

new folder

Now I want to compile "Test", it should just print "Hello, World!", but it doesn't as you can see. It compiles my "NumberCounter" program:

here

So I thought, maybe my order was incorrect. I delete my new target and the folder "test" with the main in it. Now it looks exactly like in the beginning.

I create a new C++ File "test" and now I can choose a target. I'll uncheck my "Uebung" target, because this isn't the one I want:

uncheck my "Uebung" target

Now It looks like this and this is exactly how I want it:

this

Same Procedure: I go to File -> New -> Target -> Command Line Tool and choose a name.

Again, a new folder pops out but this time it is red.

This is how my build phase looks like:

This

This isn't how I intend it to be so I change it to this:

this

Since I don't need the "test" folder I simply delete it.

I wrote down some code in my new program and compile it, but again it runs the wrong program:

wrong program.

I hope there's somebody who can help me.

Thank you very much!


Solution

  • Everything you did the first time to add the 2nd target test was correct.

    Your issue is that once you have two or more targets, you need to choose which target is the active target. Look at the titlebar at the top of the Xcode window. See the Play and Stop icons? To the right of those it says "Uebung" followed by "My Mac". Click on "Uebung" and select "test".

    Now your "test" target is active. You can now build and run that target.

    FYI - "test" appears red under Products because you have not yet built that target.