我正在尝试编译和链接PostgreSQL手册中的函数示例:
#include "postgres.h" /* this includes directly palloc.h */
#include "fmgr.h"
#include "utils/geo_decls.h" /* point type */
PG_MODULE_MAGIC;
PG_FUNCTION_INFO_V1(makepoint);
Datum makepoint(PG_FUNCTION_ARGS)
{
Point *pointx = PG_GETARG_POINT_P(0);
Point *pointy = PG_GETARG_POINT_P(1);
Point *new_point = (Point *) palloc(sizeof(Point));
new_point->x = pointx->x;
new_point->y = pointy->y;
PG_RETURN_POINT_P(new_point);
}
我已经用命令编译了它:
cc -c -fPIC -DHAVE_LONG_LONG_INT_64 -I/C:/applications/PostgreSQL/11.2.2/include/server -I/C:/applications/PostgreSQL/11.2.2/include/server/port/win32 ../src/makepoint.c
显然,它可以很好地编译,但是在链接时:
cc -shared -o makepoint.so makepoint.o
出现以下错误:
makepoint.o:makepoint.c:(.text+0x44): undefined reference to `palloc'
collect2.exe: error: ld returned 1 exit status
编译器是
cc.exe (Rev1, Built by MSYS2 project) 8.2.1 20181207
installed in MSYS on Windows 10.
(gcc或g ++也会出现相同的错误)
请帮助我理解我错误地做的事情。
预先感谢。
答案 0 :(得分:4)
虽然您已正确包含了针对PostgreSQL库进行编译所需的标头,但您并未链接创建最终可执行文件所需的任何共享库。对于Linux上的gcc,您应该将最终的编译命令更改为以下内容:
cc -c -fPIC makepoint.c -o makepoint.o
cc -shared --relocatable -o libmakepoint.so makepoint.o
cc -L/usr/local/pgsql/lib -lpq -L. -lmakepoint -o myapp.exe main.c
然后,您需要在运行时通过在环境libmakepoint.so
中定义路径或向{{添加配置},来确保动态链接器可以访问LD_LIBRARY_PATH
所在的本地目录。 1}}。您可以阅读有关该过程here的更多信息。
请注意,您的安装目录可能会有所不同,具体取决于您安装PostgreSQL的方式以及平台,但是由于您使用的是MSYS2,因此您应该能够安装ld_config
,并使用各种{ {1}},pkg-config
,--cflags
和--includedir
命令来获取适当的搜索目录和要链接到的库的名称。例如:
--libs
将输出(取决于您的配置):
--libdir
然后您可以将该字符串添加到build命令中,以链接正确的库,并将编译器指向正确的库路径。
最后,您可以reference this page以获得其他构建说明。
答案 1 :(得分:0)
您将-fPIC
选项置于构建共享库的错误阶段。它需要进入链接阶段,而不是编译阶段。这样...
cc -fPIC -shared -o makepoint.so makepoint.o
答案 2 :(得分:0)
因此,要进行编译,应使用以下命令:
cc -fPIC -DHAVE_LONG_LONG_INT_64 -c ../src/makepoint.c -I/C:/applications/PostgreSQL/12.0/include/server -I/C:/applications/PostgreSQL/12.0/include/server/port/win32
然后链接:
cc -shared -o makepoint.so makepoint.o -L/c/applications/PostgreSQL/12.0/lib -l postgres