gpt4 book ai didi

c++ - 混合从 C 和 C++ 编译的目标文件时出现链接器错误

转载 作者:行者123 更新时间:2023-11-28 01:06:01 31 4
gpt4 key购买 nike

我无法混合使用 C 和 C++ 代码,我使用 gcc 和 g++ 分别编译了 C 和 C++ 代码。 C 代码调用 C++ 函数。我分别编译它们,效果很好。我链接这两个对象以生成一个“.so”文件。当我从 lua 加载这个模块时,模块加载失败说一些 undefined symbol 。我在这里粘贴 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]: ?
>

这个 undefined symbol 是什么?

最佳答案

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

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

关于c++ - 混合从 C 和 C++ 编译的目标文件时出现链接器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6085801/

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