15

I have three files:

lib.c lib.h => They should be built as a .so file
client.c => This should be built as an executable.
Inside the client.c I include the lib.h file so as to get the declarations of the functions defined under lib.c

Can someone tell me the exact CMakeLists file that I should be using so that the source area is uncluttered with Cmake's temporary files and the binaries and the libraries (.dlls in case of windows I believe) generated in separate build and binary directories ?

Sankar
  • 6,192
  • 12
  • 65
  • 89

2 Answers2

17

This solution will not create a .so file, but a cmake equivalent for further inclusion with cmake.
I am searching for a solution with will provide the equivalent to this:

g++ -shared -Wl,-soname,plugin_lib.so.1 -o plugin_lib.so plugin_lib.o

Which will generate a plugin_lib.so that can be loaded dynamically with dlopen at runtime.

The solution is missing the "SHARED" option like so:

ADD_LIBRARY(mylib SHARED ${mylibSRCS})
chryss
  • 7,459
  • 37
  • 46
user2478081
  • 171
  • 1
  • 4
13

Cmake builds on separate build directories by default (I did not test this example):

PROJECT(myproject)
CMAKE_MINIMUM_REQUIRED(VERSION 2.8)

SET(mylibSRCS lib.c)
SET(myprogSRCS client.c)

ADD_LIBRARY(mylib ${mylibSRCS})
ADD_EXECUTABLE(myprog ${myprogSRCS})

TARGET_LINK_LIBRARIES(myprog mylib)

You do:

mkdir build
cd build
cmake ..
make

Everything would be under build.

Update: As mentioned by @chryss below, if you want the .so file to be generated, the command should be:

ADD_LIBRARY(mylib SHARED ${mylibSRCS})
Sankar
  • 6,192
  • 12
  • 65
  • 89
duncan
  • 6,113
  • 3
  • 29
  • 24
  • Is there a way to do the build always in a new directory without executing these shell commands ? I googled but could not find any useful links. – Sankar Jul 02 '12 at 15:28
  • http://stackoverflow.com/questions/11143062/getting-cmake-to-build-out-of-source-without-wrapping-scripts/11144109#11144109 – Fraser Jul 02 '12 at 23:00
  • Yes. You can `mkdir build & cd build & cmake .. & make`. If you need to super-clean your repository, just delete the build directory. This isolates the generated stuff from your original sources. – Stewart Nov 29 '16 at 09:08
  • 3
    `ADD_LIBRARY(mylib SHARED ${mylibSRCS})`, as mentioned by @chryss below. – parasrish Oct 24 '17 at 13:20