相对路径不工作在Xcode C ++ [英] Relative Paths Not Working in Xcode C++
问题描述
在网上有很多post,详细说明相对路径在Xcode中不工作。我有一个Xcode模板,我下载的相对路径工作,但我没有能够弄清楚为什么,也不复制在其他项目。
There are numerous post over the net that detail how relative paths don't work in Xcode. I do have an Xcode template that I downloaded where the relative paths DO work, however I have not been able to figure out why nor replicate it in other projects.
首先,我在Xcode 3.1中使用C ++。我不使用Objective-C,也不使用任何Cocoa / Carbon框架,只是纯C ++。
Firstly, I am using C++ in Xcode 3.1. I am not using Objective-C, nor any Cocoa/Carbon frameworks, just pure C++.
这是在我的其他Xcode模板中的代码:
Here is the code that works in my other Xcode template:
sound->LoadMusic( (std::string) "Resources/Audio/Pop.wav" );
这个相对路径也适用于Windows。运行以下命令可以得到应用程序完整路径的绝对路径:
This relative path works for me also in Windows. Running the following command gives me an absolute path to the application's full path:
std::cout << "Current directory is: " << getcwd( buffer, 1000) << "\n";
/ Applications / myApp
/Applications/myApp
我们得到了在Xcode .app包中工作的相对路径?
How can we get relative paths to work in an Xcode .app bundle?
推荐答案
告诉我5个小时的Google,最终找到答案!
Took me about 5 hours of Google and trying different things to FINALLY find the answer!
#ifdef __APPLE__
#include "CoreFoundation/CoreFoundation.h"
#endif
// ----------------------------------------------------------------------------
// 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
// ----------------------------------------------------------------------------
我抛出一些额外的包含守卫,因为这使它只编译苹果(我开发跨平台),并使代码更好。
I've thrown some extra include guards because this makes it compile Apple only (I develop cross platform) and makes the code nicer.
我感谢其他2个人的答案,你的帮助最终让我在正确的轨道找到这个答案,所以我已经投了你两个。谢谢你们!!!!
I thank the other 2 guys for your answers, your help ultimately got me on the right track to find this answer so i've voted you both up. Thanks guys!!!!
这篇关于相对路径不工作在Xcode C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!