C++最基本調用靜態庫的方法小結


同樣是最基本的調用方法小例,希望能帶來參考,感謝!
 

創建靜態庫

編輯頭文件

myLib.h:

#pragma once

#include "stdafx.h"


int add(int a,int b);

class MyClass {
public :
	MyClass() {}
	~MyClass (){}

	int val;

	int Getval(int a);

};

stdafx.h:

// stdafx.h : 標准系統包含文件的包含文件,
// 或是經常使用但不常更改的
// 特定於項目的包含文件
//

#pragma once

#include "targetver.h"

#define WIN32_LEAN_AND_MEAN             // 從 Windows 頭中排除極少使用的資料

// TODO: 在此處引用程序需要的其他頭文件

targetver.h:

#pragma once

// 包括 SDKDDKVer.h 將定義可用的最高版本的 Windows 平台。

// 如果要為以前的 Windows 平台生成應用程序,請包括 WinSDKVer.h,並將
// 將 _WIN32_WINNT 宏設置為要支持的平台,然后再包括 SDKDDKVer.h。

#include <SDKDDKVer.h>

編輯實現方法

myLib.cpp:

#include "stdafx.h"
#include "myLib.h"
int add(int a, int b)
{
	return a + b;
}

int MyClass::Getval(int a)
{
	return a * a;
}

stdafx.cpp:

// stdafx.cpp : 只包括標准包含文件的源文件
// mylib_1.pch 將作為預編譯標頭
// stdafx.obj 將包含預編譯類型信息

#include "stdafx.h"

// TODO: 在 STDAFX.H 中引用任何所需的附加頭文件,
//而不是在此文件中引用

檢查配置

配置選項選【靜態庫.lib】,點擊生成即可生成對應lib靜態庫。

 

創建EXE

編輯頭文件

myLib.h:

#pragma once

#include "stdafx.h"


int add(int a,int b);

class MyClass {
public :
	MyClass() {}
	~MyClass (){}

	int val;

	int Getval(int a);

};

stdafx.h:

// stdafx.h : 標准系統包含文件的包含文件,
// 或是經常使用但不常更改的
// 特定於項目的包含文件
//

#pragma once

#include "targetver.h"

#include <stdio.h>
#include <tchar.h>

// TODO: 在此處引用程序需要的其他頭文件

targerver.h:

#pragma once

// 包括 SDKDDKVer.h 將定義可用的最高版本的 Windows 平台。

// 如果要為以前的 Windows 平台生成應用程序,請包括 WinSDKVer.h,並將
// 將 _WIN32_WINNT 宏設置為要支持的平台,然后再包括 SDKDDKVer.h。

#include <SDKDDKVer.h>

 

編輯實現方法

mytest11.cpp:

// mytest11.cpp: 定義控制台應用程序的入口點。
//

#include "stdafx.h"
#include "windows.h"
#include "myLib.h"
#include "iostream"
int main()
{
	MyClass myc ;



	std::cout << add(5,6) << std::endl;
	std::cout << myc.val << std::endl;

	std::cout << myc.Getval(8) << std::endl;
	system("pause");
    return 0;
}


stdafx.cpp:

// stdafx.cpp : 只包括標准包含文件的源文件
// mytest11.pch 將作為預編譯標頭
// stdafx.obj 將包含預編譯類型信息

#include "stdafx.h"

// TODO: 在 STDAFX.H 中引用任何所需的附加頭文件,
//而不是在此文件中引用

檢查配置

注意靜態庫lib放入開發環境目錄中,配置選擇【應用程序.exe】即可生成。

 

結果

正常情況下雙擊運行exe可的以下結果:
image


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM