首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >链接嵌入了Python的C++对象文件

链接嵌入了Python的C++对象文件
EN

Stack Overflow用户
提问于 2020-10-03 08:54:00
回答 1查看 207关注 0票数 0

我有一个C++构造函数文件(formatting_SQ.cpp),它是一个头文件formatting_SQ.h,为了有formatting_SQ.o,我想链接到其他头文件构造函数文件(neat.cpp nnode.cpp link.cpp etc...-> neat.h nnode.h link.h)。

然后,我想将我的main.cpp文件与这个formatting_SQ.o文件链接起来。问题是:formatting_SQ是用python嵌入的,据我所知,嵌入Python的C++需要Linux上的编译标志-lpython3.6m:这样的标志需要对main()函数的引用,因为它是一个构造函数文件,在formatting_SQ.cpp中没有,因为它是一个对象文件。

因此,我首先尝试为每个构造函数文件创建对象文件,然后立即将所有内容链接到一起。

代码语言:javascript
复制
g++ -c -O3 -Wall -fPIC -fopenmp -std=c++14 -lstdc++ `python3 -m pybind11 --includes` *.cpp 
g++ -o the_executable neat.o nnode.o link.o trait.o gene.o network.o innovation.o organism.o species.o genome.o population.o formatting_SQ.o main.o -fopenmp -O3 -Wall -fPIC `python3 -m pybind11 --includes` -lpython3.6m

下面是我的第一个问题:这些命令是正确的还是最终缺少了编译标志?在我尝试执行./the_executable时,这给了我一个分段错误。

然后,我尝试使用所有其他构造函数文件独立编译formatting_SQ.cpp,但正如预期的那样,这是不起作用的,因为在formatting_SQ.cpp中没有对main的引用。

代码语言:javascript
复制
g++ -o temp_formatting neat.o nnode.o link.o trait.o gene.o network.o innovation.o organism.o species.o genome.o population.o formatting_SQ.o -fopenmp -O3 -Wall -fPIC `python3 -m pybind11 --includes` -lpython3.6m

下面是我的第二个问题:如何创建一个python对象文件,将formatting_SQ.cpp与所有其他构造函数文件连接起来,而不出现undefined reference to main错误?

formatting_SQ.cpp

代码语言:javascript
复制
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include <pybind11/stl.h>
#include <Python.h>
#include <omp.h>
#include "formatting_SQ.h"
#include "neat.h"
#include "network.h"
#include "link.h"
#include "nnode.h"
#include "trait.h"
#include "gene.h"
#include "genome.h"
#include "innovation.h"
#include "organism.h"
#include "species.h"
#include "population.h"

namespace py = pybind11;
py::module compile_data = py::module::import("initialize");

main.cpp

代码语言:javascript
复制
#include <pybind11/embed.h>
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include <pybind11/stl.h>
#include <Python.h>
#include "formatting_SQ.h"
#include <omp.h>
    
namespace py = pybind11;
        
int main(int argc, char** argv){
      
....
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-10-03 12:19:41

因此,经过长时间的研究,我可以得出结论,编译方法是正确的,但是对于从python中声明导入模块的位置非常小心,因为这是我的问题所在。

代码语言:javascript
复制
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include <pybind11/stl.h>
#include <Python.h>
#include <omp.h>
#include "formatting_SQ.h"
#include "neat.h"
#include "network.h"
#include "link.h"
#include "nnode.h"
#include "trait.h"
#include "gene.h"
#include "genome.h"
#include "innovation.h"
#include "organism.h"
#include "species.h"
#include "population.h"

namespace py = pybind11;
py::module compile_data = py::module::import("initialize"); DON'T DO THIS its wrong !!! 

您必须在本地声明模块,否则名称空间中会出现冲突,因为同一个模块可能会被多次导入,这会导致分段错误。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64182421

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档