I have trouble mixing the C and C++ code , I separately compile the C and C++ code using gcc and g++. The C code calls C++ functions. I compile them separately which go through well. I link both the objects to produce a ".so" file. when i load this module from lua , module loading fails saying some undefined symbol. I am pasting the C and C++ and the lua error here.
File: wrap.c
----------------------------------------------
#include<stdio.h>
//extern "C"{
extern const char* getMobileFromUid(long long );
extern void addToUidHash(long long, char*);
//}
int callcpp (int ac, char **av)
{
addToUidHash(1, "98866380587");
fprintf(stderr,"hash:%s",getMobileFromUid(1));
return 0;
}
File : uid_hash.cc
--------------------------------------------------------
#include <iostream>
#include <string>
#include <map>
typedef std::map<long long, std::string> uidMapType;
uidMapType uidMap;
extern "C"{
const char *getMobileFromUid(long long );
void addToUidHash(long long, char *);
}
//Add the element to the uid hash
void
addToUidHash(long long uid, char *mobile)
{
uidMap[uid] = mobile;
return;
}
//print the uid hash
void
printUidHash()
{
uidMapType::const_iterator end = uidMap.end();
for (uidMapType::const_iterator it = uidMap.begin(); it != end; ++it)
{
std::cout << "key = " << it->first;
std::cout << " value = " << it->second << '\n';
}
return;
}
//get the mobile number string from the uid of the user
const char *
getMobileFromUid(long long uid)
{
uidMapType::iterator iter = uidMap.find(uid);
if (iter == uidMap.end()) return NULL;
return iter->second.c_str();
}
I compile both of them like below
ravit@ravit-laptop:~$ g++ -c uid_hash.cc -o uid_hash.o
ravit@ravit-laptop:~$ gcc -c wrap.c -o wrap.o
ravit@ravit-laptop:~$ ld -shared wrap.o uid_hash开发者_开发问答.o -o uid_hash.so
after this i try to load the module from lua and i get an error "undefined" symbol
ravit@ravit-laptop:~$ lua
Lua 5.1.4 Copyright (C) 1994-2008 Lua.org, PUC-Rio
> require "uid_hash"
error loading module 'uid_hash' from file './uid_hash.so':
./uid_hash.so: undefined symbol: _ZNSsaSEPKc
stack traceback:
[C]: ?
[C]: in function 'require'
stdin:1: in main chunk
[C]: ?
>
what is this symbol which remains undefined ?
I think you need to link with the C++ library. c++filt can help you decode the mangled symbol name:
main% c++filt _ZNSsaSEPKc
std::basic_string<char, std::char_traits<char>, std::allocator<char> >::operator=(char const*)
精彩评论