且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

相对路径在 Xcode C++ 中不起作用

更新时间:2023-02-09 23:18:07

我花了大约 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!!!!