Search code examples
ccmakestatic-librariesstatic-linking

linking, compiling and running a c program with a static library


I'm new to C development.

A I built a library (static) in CLion

library.h

#ifndef MYLIB_LIBRARY_H
#define MYLIB_LIBRARY_H

int add(int a, int b);
int sub(int a, int b);

#endif

library.c

#include "library.h"
#include <stdio.h>

int add(int a, int b) {
    return a + b;
}

int sub(int a, int b) {
    return a - b;
}

CMakeLists.txt

cmake_minimum_required(VERSION 3.6)
project(MyLib)

set(CMAKE_C_STANDARD 99)

set(SOURCE_FILES library.c library.h)
add_library(MyLib ${SOURCE_FILES})


B. Created C Executable project called App and copied libMyLib.a into lib directory of App.

main.c

#include <stdio.h>
#include "library.h" // error

int main() {
    printf("Hello, World!\n", add(1, 2)); // error
    return 0;
}

CMakeLists.txt of the project App and specified folder for the linker.

cmake_minimum_required(VERSION 3.6)
project(App)

set(CMAKE_C_STANDARD 99)

set(SOURCE_FILES main.c)
link_directories(${PROJECT_SOURCE_DIR}/lib)
add_executable(App ${SOURCE_FILES})

Question. How can I make my program work using static library?


Solution

  • There's a couple of things I had to change to get your example to work:

    1. Create an include directory in the App directory.
    2. Put library.h in this include directory.
    3. Modify the project CMakeLists.txt file:

      cmake_minimum_required(VERSION 3.6)
      project(App)
      
      set(CMAKE_C_STANDARD 99)
      set(SOURCE_FILES main.c)
      # get libMyLib.a
      find_library(MY_LIB
          NAMES libMyLib.a
          PATHS ${PROJECT_SOURCE_DIR}/lib)
      # get library.h
      include_directories(${PROJECT_SOURCE_DIR}/include)
      
      add_executable(App ${SOURCE_FILES})
      # link App with libMyLib.a
      target_link_libraries(App ${MY_LIB})