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

Libraries have to come after the object files when you are linking, so do:

gcc  embedpy.o $(/usr/bin/python2.7-config --ldflags)

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 <Python.h>

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