windows制作lib静态库

windows制作lib静态库

编译链接

写几对c和h

// math_operations.c
#include "math_operations.h"

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

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

// math_operations.h
#ifndef MATH_OPERATIONS_H
#define MATH_OPERATIONS_H
 
int add(int a, int b);
int subtract(int a, int b);

#endif // MATH_OPERATIONS_H

编译:

cl /c math_operations.c

此时生成math_operations.obj

// tt.h
#ifndef TT_H
#define TT_H

int invokemessagebox(LPCSTR context,LPCSTR title);

#endif // TT_H


//tt.c
#include <windows.h>

int invokemessagebox(LPCSTR context , LPCSTR title){
    MessageBox(
        NULL,
        context,
        title,
        MB_ICONINFORMATION | MB_OK
        );
  
    return 0;
}

同样的方式编译:

cl /c tt.c

此操作将生成文件tt.obj

下面将多个obj文件制作成lib文件:

lib /OUT:mylibrary.lib math_operations.obj tt.obj

生成的lib文件即为供使用的静态库二进制文件,使用时候include对应的h文件,在链接参数添加对应的lib文件.

#include <stdio.h>
#include <windows.h>
#include "math_operations.h"
#include "tt.h"

int main() {

    int result = add(10, 5);
    printf("Addition result: %d\n", result);
    result = subtract(10, 5);
    printf("Subtraction result: %d\n", result);
    
    LPCSTR b = "Title";
    LPCSTR a = "Context";
    invokemessagebox(a,b);
    
    return 0;
}

使用如下命令链接静态库

cl main.c /link /DEFAULTLIB:mylibrary.lib user32.lib

由于tt.c中引入了windows.h,文件链接时候还需要添加user32.lib才能找到tt中引入的符号,否则会报错;

posted @ 2024-02-29 20:56  bfhyqy  阅读(24)  评论(0编辑  收藏  举报