简体   繁体   English

尝试编译嵌入 Python 的 C 代码时出现链接错误

[英]Linking error trying to compile C code embedded with Python

I'm trying to import and run this python function inside C code:我正在尝试在 C 代码中import并运行此 python function :

import requests
import json

url = 'http://127.0.0.1:5000/'


def verify():
    code = input('Show-me the code: ')
    r = requests.post(url, data=json.dumps({'code': code}))
    return r.json()

Here is the C code:这是 C 代码:

#include <Python.h>

int main(void){

    PyObject *myModuleString, *myModule, *myFunction, *myResult;

    Py_Initialize();

    myModuleString = PyUnicode_FromString((char*)"verify");
    myModule = PyImport_Import(myModuleString);

    myFunction = PyObject_GetAttrString(myModule,(char*)"verify");
    myResult = PyObject_CallObject(myFunction, NULL);

    const char* s = PyUnicode_AsUTF8(myResult);
    printf("REPR: %s\n", s);

    Py_Finalize();

    return 0;
}

Create the object file works fine:创建 object 文件可以正常工作:

$ gcc -c `python3.7-config --cflags --ldflags` source_code.c
$

But it does not work at the end:但它最终不起作用:

$ gcc source_code.o -o source_code.bin
/usr/bin/ld: source_code.o: relocation R_X86_64_32 against `.rodata.str1.1' can not be used when making a PIE object; recompile with -fPIE
/usr/bin/ld: final link failed: nonrepresentable section on output
collect2: error: ld returned 1 exit status

The -fPIE argument also does not help: -fPIE参数也无济于事:

$ gcc -c `python3.7-config --cflags --ldflags` -fPIE  source_code.c
$
$ gcc source_code.o -o source_code.bin
/usr/bin/ld: source_code.o: in function `main':
/home/user/source_code.c:7: undefined reference to `Py_Initialize'
/usr/bin/ld: /home/user/source_code.c:9: undefined reference to `PyUnicode_FromString'
/usr/bin/ld: /home/user/source_code.c:10: undefined reference to `PyImport_Import'
/usr/bin/ld: /home/user/source_code.c:12: undefined reference to `PyObject_GetAttrString'
/usr/bin/ld: /home/user/source_code.c:13: undefined reference to `PyObject_CallObject'
/usr/bin/ld: /home/user/source_code.c:15: undefined reference to `PyUnicode_AsUTF8'
/usr/bin/ld: /home/user/source_code.c:18: undefined reference to `Py_Finalize'
collect2: error: ld returned 1 exit status

How can I define the references to generate the binary file?如何定义生成二进制文件的引用?

I had a similar error.我有一个类似的错误。 Adding the -no-pie argument to the compile statement worked for me.-no-pie参数添加到 compile 语句对我有用。 You could try this:你可以试试这个:

gcc -c `python3.7-config --cflags --ldflags` source_code.c -no-pie

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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