网上有很多帖子详细说明了相对路径在 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) << "
";
/应用程序/myApp
/Applications/myApp
我们如何获得在 Xcode .app 包中工作的相对路径?
How can we get relative paths to work in an Xcode .app bundle?
我花了大约 5 个小时的谷歌和尝试不同的东西终于找到了答案!
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
// ----------------------------------------------------------------------------
我抛出了一些额外的包含守卫,因为这使得它只能编译 Apple(我开发跨平台)并使代码更好.
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++ 中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!