简体   繁体   中英

Properly defining namespaces with anonymous functions

I'm a bit confused with C++ namespaces, and how you define them. I have two files: Lua.h and Main.cpp . Lua.h contains the following helpers for running Lua scripts in a namespace:

#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

My Main.cpp files tries to run a Lua script using these helper functions:

#include "Lua.h"

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

But when I try to compile Main.cpp , I get this:

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

I'm just confused on how to define this namespace. The code for the helper functions is all good, but Main.cpp can't find the namespace. Can anyone give me some pointers on how to define this namespace correctly in C++?

EDIT :

Works now. For some reason my -I flag wasn't working on compile since I had my headers under Include/ . I also renamed Lua.h to LuaHelpers.h .

I guess there's a conflict between your Lua.h and Lua's Lua.h. Consider renaming your file to fabric.h or something like that.

That said, putting non-inline functions into a header file will cause linker errors when the file is included into two translation units. Consider splitting the code into the typical header/implementation pair.

Maybe the reason is, the Lua library has also the file, plus you are working on Windows, so the file system is case insensitive?

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"
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM