Embedding Python in C, linking fails with undefined reference to `Py_Initialize'

前端 未结 5 1409
陌清茗
陌清茗 2021-02-14 02:21

I am trying to compile the example from the docs https://docs.python.org/2.7/extending/embedding.html and my code looks exactly like the one under 5.1:

#include          


        
5条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-14 03:12

    Also add --embed to python3-config

    On Ubuntu 20.04, Python 3.8, I also needed to pass --embed to python3-config as in:

    gcc -std=c99 -ggdb3 -O0 -pedantic-errors -Wall -Wextra \
      -fpie $(python3-config --cflags --embed) -o 'eval.out' \
      'eval.c' $(python3-config --embed --ldflags)
    

    otherwise -lpython3.8 is not added which leads to missing definitions.

    This is my test program:

    eval.c

    #define PY_SSIZE_T_CLEAN
    #include 
    
    int main(int argc, char *argv[]) {
        (void)argc;
        wchar_t *program = Py_DecodeLocale(argv[0], NULL);
        if (program == NULL) {
            fprintf(stderr, "Fatal error: cannot decode argv[0]\n");
            exit(1);
        }
        Py_SetProgramName(program);
        Py_Initialize();
        PyRun_SimpleString(argv[1]);
        if (Py_FinalizeEx() < 0) {
            exit(120);
        }
        PyMem_RawFree(program);
        return 0;
    }
    

    test run:

    ./eval.out 'print(2 ** 3)'
    

提交回复
热议问题