Reputation: 57
I'm writing a C program in Xcode 4.4.1. A new project starts me off with a main.c file which is obviously my main file. What if I want to write a different program? If I choose File>New File, Xcode creates a new .c file next to main.c. The trouble is that when I place code in that new file, when I attempt to run it, I get a build error having to do with linking. I can always take the code from program2 and paste it into a brand new project in the main.c file and it will work but, for organization purposes(college work), I'd prefer to just have multiple files in the same project which can be independently compiled and executed. I'm very new to Xcode, so I ask, what am I doing wrong/not understanding?
I have pics to post but I'm not able due to my just having registered this account. Thanks in advance!
Upvotes: 3
Views: 4764
Reputation: 22948
You can use a single Xcode project but create multiple targets in said project.
To add a second target, click the Add target button like shown in the image below:
Like you did originally in the New Project window, add a target for a C-based Command Line Tool like in the image below:
This creates another folder inside your project folder that holds the main.c file for the newly added target. The new target will be set up with a "Compile Sources" build phase that only builds the newly created main.c
file and not the main.c
files from any other targets, thus alleviating the build errors you were getting before.
To control which target you want to work with, choose the appropriately named scheme from the scheme popup menu in the toolbar.
Upvotes: 2
Reputation: 726579
I get a build error having to do with linking.
Let me guess: your other file contains a main
function. A project is not allowed to have multiple main
functions (in fact, all non-static functions must have unique names). The main
does not need to be in the main.c
file, but there needs to be exactly one main
.
One solution is to rename the functions in other files except the one that you want to run to something else (main2
, main3
, and so on). This will stop the linker from complaining.
However, this approach is error-prone. The standard approach is to use multiple projects - one for each program that you write. You can keep them in the same Xcode workspace for convenience, but each one should have a separate target and its own main.c
file.
Upvotes: 1