我在混合C和C ++代码时遇到麻烦,我分别使用gcc和g ++编译C和C ++代码。 C代码调用C ++函数。我分别编译它们,一切顺利。我将两个对象链接在一起以生成一个“ .so”文件。当我从lua加载此模块时,模块加载失败,提示一些未定义的符号。我在这里粘贴C和C ++和lua错误。

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]: ?
>


这个未定义的符号是什么?

最佳答案

我认为您需要与C ++库链接。 c ++ filt可以帮助您解码错误的符号名称:

main% c++filt _ZNSsaSEPKc
std::basic_string<char, std::char_traits<char>, std::allocator<char> >::operator=(char const*)

09-06 04:35