0

我对 C++ 命名空间以及您如何定义它们有点困惑。我有两个文件:Lua.hMain.cpp. Lua.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标志无法编译,因为我的标题位于Include/. 我也改名Lua.hLuaHelpers.h.

4

2 回答 2

1

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

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

于 2013-05-14T17:47:18.773 回答
1

可能原因是 Lua 库也有文件,加上你在 Windows 上工作,所以文件系统不区分大小写?

lua.hpp

// lua.hpp
// Lua header files for C++
// <<extern "C">> not supplied automatically because Lua also compiles as C++

extern "C" {
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
}
于 2013-05-14T18:28:05.300 回答