简体   繁体   English

使用静态库链接,编译和运行ac程序

[英]linking, compiling and running a c program with a static library

I'm new to C development. 我是C开发的新手。

A I built a library (static) in CLion A I在克利翁建库(静态)

library.h 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 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 的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. B.创建一个名为App的C可执行项目,并将libMyLib.a复制到App的lib目录中。

main.c 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. 项目App的CMakeLists.txt和链接器的指定文件夹。

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. 在App目录中创建一个include目录。
  2. Put library.h in this include directory. library.h放在此包含目录中。
  3. Modify the project CMakeLists.txt file: 修改项目CMakeLists.txt文件:

     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() 原因是将printf()函数作为第一个参数(格式字符串)传递给Hello, World!\\n和第二个参数: add(1,2)但是,格式字符串中没有用于格式的说明符。调用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 在更正编译问题之前,没有理由要查看Cmakelists.txt文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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