How to make XCode put required resources in "build" folder? - c++

I am trying out lua script with C++ in Mac OS X. I was finding a way to make the program returning the current working directory. That's no problem with getcwd, but then I came one thing:
My foo.lua stays at its initial path only. When I compile program, it is not being copied over to the build/Debug directory. Sure, I can grab my script there, but that's just impractical. XCode or any IDE should carry resources to the build zone. XCode does this automatically with iPhone app, but this seems to be a different case. For this case, how to command XCode to put the respective resources in the build directories?
int main (int argc, char * const argv[]) {
...
...
luaL_dofile(luaVM,"/Users/yourNameHere/Desktop/LuaSandbox/LetsTryLua/foo.lua");
//typing the whole absolute path here is just ugly and impractical.
...
...
printf("working directory: %s", buffer);
//output is: working directory: /Users/yourNameHere/Desktop/LuaSandbox/LetsTryLua/build/Debug
...
...

Rather than hard code the path to your Lua script you may want to use the NSBundle API's to find it:
NSBundle * mainNSBundle = [NSBundle mainBundle];
NSString * luaFilePath = [mainNSBundle pathForResource:#"foo"
ofType:#"lua"
inDirectory:NULL
forLocalization:NULL];
luaL_dofile(luaVM,[luaFilePath UTF8String]);
This will find it in the bundle's folder (if you added the "Copy Bundle Resources" build step to your target as the above poster suggested.

Because you're using a .lua file as a resource, I suspect that isn't recognised as a standard resource type and hence it hasn't been automatically copied. You should be able to do this though by adding an extra Copy Bundle Resources build step to your target and then add your file to it in the project view.

If you're creating a command line tool that is not a bundle, then there's never going to be a good solution. If you're creating a regular app then the aforementioned solution will work, but you're going to have to stop assuming that your working directory is set to anything even remotely meaningful at any point in time and use the appropriate methods for finding resources stored within your bundle.

Related

"Embedding" a folder into a C/C++ program

I have a script library stored in .../lib/ that I want to embed into my program. So far, that sounds simple: On Windows, I'd use Windows Resource Files - on MacOS, I'd put them into a Resource folder and use the proper API to access the current bundle and it's resources. On plain Linux, I am not too sure how to do it... But, I want to be cross-platform anyway.
Now, I know that there are tools like IncBin (https://github.com/graphitemaster/incbin) and alike, but they are best used for single files. What I have, however, might even require some kind of file system abstraction.
So here is the few guesses and estimates I did. I'd like to know if there is possibly a better solution - or others, in general.
Create a Zip file and use MiniZ in order to read it's contents off a char array. Basically, running the zip file through IncBin and passing it as a buffer to MiniZ to let me work on that.
Use an abstracted FS layer like PhysicsFS or TTVFS and add the possibility to work off a Zip file or any other kind of archive.
Are there other solutions? Thanks!
I had this same issue, and I solved it by locating the library relative to argv[0]. But that only works if you invoke the program by its absolute path -- i.e., not via $PATH in the shell. So I invoke my program by a one-line script in ~/bin, or any other directory that's in your search path:
exec /wherever/bin/program "$#"
When the program is run, argv[0] is set to "/wherever/bin/program", and it knows to look in "/wherever/lib" for the related scripts.
Of course if you're installing directly into standard locations, you can rely on the standard directory structure, such as /usr/local/bin/program for the executable and /etc/program for related scripts & config files. The technique above is just when you want to be able to install a whole bundle in an arbitrary place.
EDIT: If you don't want the one-line shell script, you can also say:
alias program=/wherever/bin/program

Difficulty in using SDL_LoadBMP with relative path in Xcode

Firstly, I know this question has been asked many, many times; I have read at least five or ten variations, but none of the answers given worked in my case. I have the line:
helloWorld = SDL_LoadBMP("helloworld.bmp");
in the main.cpp file of my Xcode 5 project. The directory structure is as follows:
TestProject1
main.cpp
Resources
helloworld.bmp
TestProject1.1
TestProject1.xcodeproj
Of course, I have tried different paths, i.e. Resources/helloworld.bmp, and yes, the Resources folder is imported into the project. However, the statement returns NULL because (according to SDL_Error) it cannot find the file. Now, the line:
helloWorld = SDL_LoadBMP("/fully/qualified/path/to/helloworld.bmp");
works fine, so it is not a problem with my code. What is the generally accepted way to get Xcode to work with relative paths for resources? I am looking for a method that will be portable (to the platforms that SDL supports, ofc on different computers/devices) when I make a larger project, and am open to using a different IDE if Xcode cannot make portable C++ projects. Miscellaneous other things I have tried after reading other questions:
Adding helloworld.bmp to Build Phases > Copy Files.
Adding the code:
// ----------------------------------------------------------------------------
// This makes relative paths work in C++ in Xcode by changing directory to the Resources folder inside the .app bundle
#ifdef __APPLE__
CFBundleRef mainBundle = CFBundleGetMainBundle();
CFURLRef resourcesURL = CFBundleCopyResourcesDirectoryURL(mainBundle);
char path[PATH_MAX];
if (!CFURLGetFileSystemRepresentation(resourcesURL, TRUE, (UInt8 *)path, PATH_MAX))
{
// error!
}
CFRelease(resourcesURL);
chdir(path);
std::cout << "Current Path: " << path << std::endl;
#endif
// ----------------------------------------------------------------------------
to the beginning of main.cpp (returns "Expected unqualified-id" compiler error on the if (!CFURL...) line).
Using an absolute path - as I said, this works, but I want portability.
Calling getcwd: this is C++ code. Is there something I am missing here? It doesn't seem like getcwd is a C++ function.
In your Build Phases you need to create a new build phase of type Copy Files.
Set Destination to be 'Resources' and leave Subpath blank unless you want to have a subfolder in your resources (can be useful when you have a lot and want to separate eg fonts, textures, sounds etc)
Leave Copy only when installing unticked
Then just add the resources to that build phase, in your case helloworld.bmp
You should then be able to load by doing:
helloWorld = SDL_LoadBMP("helloworld.bmp");
or if you used a Subpath:
helloWorld = SDL_LoadBMP("textures/helloworld.bmp");
This is the same sort of way you could bundle the SDL2.framework with your application. There is a tutorial here - http://zamma.co.uk/setup-sdl2-in-xcode-osx/ and in Part 3 it describes how to bundle the frameworks if you are interested.
Overal though the best way to do fully portable builds is going to be something like CMake or Gradle.

QMake - how to add a post-build step after EVERY build

Having a bit of trouble - I've added the following lines to qmake in order to get it to copy files into the app bundle on Mac.
mac {
QMAKE_POST_LINK = $$PWD/package_mac.sh
}
The .sh file runs sometimes, and seems to work (at the moment it just runs touch geese which creates a file named geese in the build directory (excellent!).
But, it doesn't run every time I build, it seems to be only when files are changed. Really, I want a way to get qmake to copy over all my game's resources into the correct places on each platform (so build folder on Windows, app package on Mac, etc...) every time I build.
Any ideas?
Have you tried using POST_TARGETDEPS (with QMAKE_EXTRA_TARGETS)? The downside to this approach is that you'll have to create some sort of dummy file (since to the best of my knowledge .PHONY isn't supported by qmake), which you should probably also clean later.
Taking your example:
mac {
package-script = $$PWD/package_mac.sh
}
package-target.target = $$PWD/package.tmp
package-target.depends = FORCE
package-target.commands = $$package-script
(See this question for a similar discussion.)

WxWidgets - Unable to load images

I recently started working with WxWidgets (2.9.4) and was working through a tutorial I found, but it seems that I'm unable to load any images. I've already properly used the handler (for PNG) and the problem happens at run-time. Below is an image of the popup that is displayed when attempting to run the program.
Here is the code:
wxPNGHandler *handler = new wxPNGHandler;
wxImage::AddHandler(handler);
wxBitmap exit;
exit.LoadFile(wxT("exit.png"), wxBITMAP_TYPE_PNG);
wxToolBar *toolbar = CreateToolBar();
toolbar->AddTool(wxID_EXIT, exit, wxT("Exit"));
toolbar->Realize();
Connect(wxID_EXIT, wxEVT_COMMAND_TOOL_CLICKED, wxCommandEventHandler(mainWindow::exitProg));
Any help is appreciated.
EDIT: I forgot to mention that when I click Cancel, this happens:
I placed the exit.png file in the build directory (/Debug or /Release) as well as the source code directory, but it still has yet to see it.
What is your working directory?
If you are using visual studio and running using the interface ( F5 or ctrl-F5 or the little run button in the toolbar ) then your working directory is the folder containing the project file. So try copying your image file there.
Or open a command window, cd to one of your build directories, and run your app from the command line.
In general, to avoid this sort of problem, I alter the project properties so that the executable is NOT stored in one of the build folders, but in a new folder ( which I usually call 'bin' - my unix roots are showing! ) and also alter the debugging properties so that the working directory is the bin folder.
There are a couple of advantages to this technique:
Both the release and trhe debug version use the same folder, so you only need one copy of any extra file, like your image file.
It is easy to see the executable and extra files in the working directory without being distracted by all the .obj files that end up in the build folders
IMHO this is well worth the little extra trouble in maintaining non default project properties.
First of all, to avoid problems deep inside wxToolBar, always check the return code of LoadFile() or, alternatively, use wxBitmap::IsOk() to check that the bitmap was successfully loaded.
Second, while adding the handler explicitly as you did is perfectly fine, I'd recommend to just call wxInitAllImageHandlers() as it's simpler and has no real drawbacks unless you are looking to create the smallest program possible.
Finally, to address your real problem, the file clearly doesn't exist at the path you're loading it from. You can, of course, solve this by being careful not to change your working directly (or restore it after changing it) in your program and by placing the file in the correct place. But this is, as you discovered, error-prone, so a better idea is to always use full paths to your resources. To construct them, you will find wxStandardPaths useful, in particular its GetResourcesDir() method.

Where to start for writing a shell script for copying elements into main app xcode4

I am looking for some documentation or tutorial for copying files from a given directory into the app created by xcode at build time, before it is run.
At first I have tried to copy files into the derived directory, hoping that everything resides in there would be automatically added to the app, but I was wrong.
So I am looking for a script because the original dir may change its name, second the script could be customized by another xcode 4 user with its src dir path etc.
The things is I don't know how to start, which language etc. I am quite confident with shell script, but maybe there's a better option.
Second, I am trying to figure out which command could add a file in the already built app.
thanks
That answer didn't really help - the BUILT_PRODUCT_DIR isn't where most stuff goes.
Ultimately, I found you just need to do:
Add the following to the very end of your script (or get your script to write directly to the output location):
cp ${DERIVED_FILE_DIR}/[YOUR OUTPUT FILES] ${BUILT_PRODUCTS_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}
...but there's a lot of other things I tried. More thoughts and ideas here: http://red-glasses.com/index.php/tutorials/xcode4-a-script-that-creates-adds-files-to-your-project/
You want a Run Script or Copy Files build phase. Select your main project in the navigator, then select the app's target. Click the Build Phases tab. Click the Add Build Phase button at the bottom of the window and choose the appropriate phase.
By "appropriate" I mean if you really want to run a script, you'll use a Run Script build phase and use Xcode-provided environment variables like $BUILT_PRODUCT_DIR (see the documentation or hit build and examine the full output of an empty script in the build log) to figure out your target folder. If all you want to do is copy files (no real processing), the Copy Files build phase already knows how to locate the app bundle's proper folders depending on what you're copying (Resources, Frameworks, etc.).