Search code examples
c++linkerclangstatic-librariesdynamic-library

Create STATIC and SHARED libraries with Clang


What is the minimal commmand line way to create an static and a dynamic library with Clang under Linux and Windows, and then, link it against an executable?

Suppose the project contains a main.cpp file with the main function, an lib_header.h file under /include/project_name and a lib_source.c or lib_source.cpp under /src

Thanks


Solution

  • For both static and dynamic libraries, you first compile the source files individually:

    clang -c -o lib_source.o lib_source.c -fPIC
    

    For the static library on Linux, archive all .o files together:

    ar r library.a lib_source.o
    

    For the shared library, link with the -shared flag:

    clang -shared -o library.so lib_source.o