Create STATIC and SHARED libraries with Clang
Asked Answered
I

1

11

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

Immature answered 6/2, 2022 at 21:47 Comment(0)
I
18

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
Immixture answered 6/2, 2022 at 21:51 Comment(4)
You need to mention -fPIC for shlibs.Deportation
Quite simple and perfect explanation. Thanks.Immature
The ` -fPIC ` (Position-Independent Code) flag is not required when generating a static libraryHawken
For me it turned out that the compiler expected to have the .so formatted in the following way: lib{name}.so where {name} is the same as when doing the compilation with the -l{name} flag. Example: Compile the source file: clang -c -o libtcp.o /workspaces/library_dir/tcp.c Compile a static library ar r libtcp.a libtcp.o Compile it together with the main file: clang++ main_file.o -l tcp -L /workspaces/library_dir/Circumscription

© 2022 - 2024 — McMap. All rights reserved.