gpt4 book ai didi

c++ - 使用匿名函数正确定义命名空间

转载 作者:行者123 更新时间:2023-11-28 03:17:04 27 4
gpt4 key购买 nike

我对 C++ namespace 以及您如何定义它们有点困惑。我有两个文件:Lua.hMain.cppLua.h 包含以下用于在命名空间中运行 Lua 脚本的帮助程序:

#ifndef Lua_h
#define Lua_h

#include <lua.hpp>

namespace fabric
{
namespace lua
{
void loadLibs(lua_State * L)
{
static const luaL_Reg luaLibs[] =
{
{ "io", luaopen_io },
{ "base", luaopen_base },
{ NULL, NULL }
};

const luaL_Reg * lib = luaLibs;
for (; lib->func != NULL; lib++)
{
lib->func(L);
lua_settop(L, 0);
}
}

void init(lua_State * L)
{
loadLibs(L);
luaL_dofile(L, "Init.lua");

lua_close(L);
}
}
}

#endif

我的 Main.cpp 文件尝试使用这些辅助函数运行 Lua 脚本:

#include "Lua.h"

int main (int argc, char * argv[])
{
fabric::lua::init();
return 0;
}

但是当我尝试编译 Main.cpp 时,我得到了这个:

Source/Main.cpp:9:3: error: use of undeclared identifier 'fabric'
fabric::lua::init();
^

我只是对如何定义这个命名空间感到困惑。辅助函数的代码都很好,但是 Main.cpp 找不到命名空间。谁能给我一些关于如何在 C++ 中正确定义此命名空间的指示?

编辑:

现在工作。出于某种原因,我的 -I 标志在编译时不起作用,因为我的 header 位于 Include/ 下。我还将 Lua.h 重命名为 LuaHelpers.h

最佳答案

我猜你的Lua.h和Lua的Lua.h有冲突。考虑将您的文件重命名为 fabric.h 或类似名称。

也就是说,将非内联函数放入头文件中,当文件包含在两个翻译单元中时,会导致链接器错误。考虑将代码拆分为典型的 header /实现对。

关于c++ - 使用匿名函数正确定义命名空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16549529/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com