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

问题描述 投票:0回答:1

我正在尝试import并在C代码中运行此python函数:

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()

这是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;
}

创建目标文件工作正常:

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

但是最后它不起作用:

$ 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

-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

如何定义引用以生成二进制文件?

python c python-3.x linux gcc
1个回答
0
投票

我有类似的错误。在编译语句中添加-no-pie参数对我来说很有效。您可以尝试以下方法:

gcc -c `python3.7-config --cflags --ldflags` source_code.c -no-pie
© www.soinside.com 2019 - 2024. All rights reserved.