建立靜態函式庫(Static Library)

發表於 四月 28, 2008. 分類: C/C++ |

此範例為Visual C++ 6.0建立一個Static Library(LIB檔),再將此函庫供其它程式應用。

首先建立一個函式庫(LIB檔),用Visual C++ 6.0 建立一個Win32 Static Library專案,專案名稱為 hellolib,然後新增一個hellolib.cpp及hellolib.h,在 hellolib.cpp定義一個簡單的加法函式如下

#include "hellolib.h"

int num_add(int x, int y, int *z)
{
    *z = (x + y);

    return 0;
}

然後在 hellolib.h 宣告 int num_add(int x, int y, int *z);

完成後就直接Build,成功後將會產生一個hellolib.lib檔案

再來建立一個console mode ap測試剛剛所建立的static library,建立一個Win32 Console Application,專案名稱為uselib,手動建立一個uselib.cpp,再將剛剛所產生的hellolib.lib與hellolib.h複製到uselib的專案下(不一定要在uselib專案下,只要待會指定時能讓complier及linker找到這兩個檔即可),在uselib.cpp寫一個測試lib檔函式,如下

#include <stdio.h>
#include "hellolib.h"    //引用hellolib.h檔使其complier能知道所使用的函式名稱

int main(void)
{
    int x, y, z, ret;
    int *pz = NULL;
    x = 13;
    y = -14;
    z = 0;
    pz = &z;
    ret = 0;
    ret = num_add(x, y, pz);

    if(ret == 0)
    {
        printf("%d + %d = %d\n", x, y, z);
    }

    return 0;
}

接下來要link lib檔,
方法一: Project | Settings | Link Tab | Object/library modules: | 加入hellolib.lib(路徑不同,請指定路徑)。

方法二:在FileView加入hellolib.lib,至於是正確的加在Source Files或Header Files都可以,我的做法是建立一個lib的目錄,再將所開發好的lib檔加入lib目錄裡,沒有什麼原因,較好了解管理。

方法三:在 uselib.cpp 的 #include <stdio.h> 最上面加上 #pragma comment(lib, “hellolib.lib"),這樣 compiler 就知道去 linker hellolib.lib。

接下來就可以直接Build,編譯會成功,但link時會出現一個 LINK : warning LNK4098: defaultlib “LIBC" conflicts with use of other libs; use /NODEFAULTLIB:library 的警告,不過程式可以正常執行,若不想看到這個警告訊息,可到 Project | Settings | Link Tab | Project Options: | 加入 /NODEFAULTLIB:"LIBC" 再重新編譯即可,至於出現這樣的訊息可能是與預設的library版本不符,再找看看這方面資料。

Make a Comment

發表迴響

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 變更 )

Twitter picture

You are commenting using your Twitter account. Log Out / 變更 )

Facebook照片

You are commenting using your Facebook account. Log Out / 變更 )

連結到 %s

2 回應 to “建立靜態函式庫(Static Library)”

RSS Feed for 大熊寶店 Jiashyang’s Weblog Comments RSS Feed

我都有照上面的步驟
可是還是出現fatal error C1083: Cannot open include file: ‘hellolib.h’: No such file or directory
真奇怪…

以上為基本的一個專案從無到有建立流程,依照每個人電腦的環境設定會有一點點要調整。


Where's The Comment Form?

Liked it here?
Why not try sites on the blogroll...

Follow

Get every new post delivered to your Inbox.