How to use pkg-config to link a library statically

前端 未结 4 967
心在旅途
心在旅途 2021-01-05 12:08

I\'d like to link libpng found by pkg-config statically.

pkg-config --libs --static libpng

outputs

-L/usr/local/Cell

4条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-05 12:50

    You could edit the .pc file to make it support static linking, especially if you are in a position to be compiling, patching, and installing software yourself instead of relying on some Linux distribution.

    Here is an example of a .pc file that supports both dynamic and static linking. This is taken from /usr/lib/x86_64-linux-gnu/pkgconfig/xcb.pc on my Ubuntu system:

    prefix=/usr
    exec_prefix=${prefix}
    libdir=${prefix}/lib/x86_64-linux-gnu
    includedir=${prefix}/include
    xcbproto_version=1.11
    
    Name: XCB
    Description: X-protocol C Binding
    Version: 1.11.1
    Requires.private: pthread-stubs xau >= 0.99.2 xdmcp
    Libs: -L${libdir} -lxcb
    Libs.private: 
    Cflags: -I${includedir}
    

    If you run pkg-config --libs xcb, it assumes you want the dynamic version and it gives you just -lxcb. The xcb.so dynamically shared object will know how to load all of its own dependencies so you don't have to specify them when linking against it.

    If you run pkg-config --libs xcb --static, then the .private fields come into play, and you get -lxcb -lXau -lXdmcp.

    I have not encountered many build systems that know to pass the --static argument to pkg-config. So if your .pc file is only intended to support static linking, it's probably best to not use .private fields, and just provide all the dependencies people will need unconditionally. That way people can link against the library successfully even if they don't know it's static or don't know to pass --static to pkg-config.

提交回复
热议问题