简体   繁体   中英

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?

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}) 

This line:

printf("Hello, World!\n", add(1, 2)); // error

is generating an error at compile time, not link time

The reason is the printf() function is being passed as the first argument (the format string) Hello, World!\\n and the second argument: add(1,2) However, there is no format specifier in the format string for the results of the call to add()

The compiler will output the message:

warning: too many arguments for format [-Wformat-extra-args]

There is no reason to be looking at the Cmakelists.txt file until after correcting the compile problems

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM