You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

构建Python C扩展共享库时遭遇struct timespec编译错误

解决Python扩展库编译时的struct timespec报错问题

错误原因

启用-std=c99编译选项时,C标准库的<time.h>默认不会暴露POSIX扩展定义的struct timespec,但Python内部头文件pytime.h直接使用了该结构体,加上你开启了-Werror(将警告视为错误),编译器就抛出了结构体声明不可见的错误。

三种解决办法

1. 在代码中添加特性测试宏

在代码最顶部添加宏定义,强制<time.h>暴露POSIX扩展内容:

#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <time.h>
#include <Python.h>

/**
 * print_python_list_info - 打印Python列表的相关信息
 * @p: 对象
 * Return: 无返回值
 */
void print_python_list_info(PyObject *p)
{
        long int size, index = 0, allocations;
        PyObject *obj;

        size = PyList_Size(p);
        allocations = ((PyListObject *)p)->allocated;

        printf("[*] Size of the Python List = %ld\n", size);
        printf("[*] Allocated = %ld\n", allocations);

        for (index = 0; index < size; index++)
        {       
                obj = PyList_GetItem(p, index);
                printf("Element %ld: %s\n", index, Py_TYPE(obj)->tp_name);
        }
}

2. 修改编译命令,添加宏定义

在gcc命令中加入-D_POSIX_C_SOURCE=200809L参数,无需修改代码:

gcc -Wall -Werror -Wextra -pedantic -std=c99 -shared -Wl,-soname,PyList -o libPyList.so -fPIC -I/usr/include/python3.10 -D_POSIX_C_SOURCE=200809L 100-print_python_list_info.c

3. 移除-std=c99编译选项

如果不需要严格遵循C99标准,直接去掉该选项,gcc默认使用gnu99模式(包含POSIX扩展支持):

gcc -Wall -Werror -Wextra -pedantic -shared -Wl,-soname,PyList -o libPyList.so -fPIC -I/usr/include/python3.10 100-print_python_list_info.c

内容的提问来源于stack exchange,提问作者Waheed Elhariri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 23:07:32