Parse VC Create DLL, export global variables, functions and classes of in-depth analysis _c language

Source: Internet
Author: User
I. Creating a DLL
1. In VC, a new Win32 empty project mathlib;
2. Add precompiled Header file stdafx.h, define import export control symbols:
Copy Code code as follows:

StdAfx.h
#pragma once
#define Mathlib_export

3. Add the header file MathLib.h that contains the global variables, functions, and classes to export:
Copy Code code as follows:

MathLib.h
#pragma once

#ifdef Mathlib_export
#define MATHLIBAPI __declspec (dllexport)
#else
#define MATHLIBAPI __declspec (dllimport)
#endif

Macro
#define PI 3.14149

Global variable
extern Mathlibapi int globalvariable;

Function
MATHLIBAPI int Add (int a,int b);

Class
Class Mathlibapi Math
{
Public
int Multiply (int a,int b);
};

4. Add the implementation file for the exported element MathLib.cpp
Copy Code code as follows:

MathLib.cpp
#include "stdafx.h"
#include "MathLib.h"

int globalvariable = 100;

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

int math::multiply (int a,int b)
{
return a*b;
}

Two, test the DLL you created
Test code:
Copy Code code as follows:

#include "stdafx.h"
#include <iostream>
using namespace Std;

#include ". /mathlib/mathlib.h "
#pragma comment (lib, "...). /debug/mathlib.lib ")

int _tmain (int argc, _tchar* argv[])
{
cout<< "Pi =" <<PI<<endl;

cout<< "globalvariable =" <<GlobalVariable<<endl;

int a = 20,b = 30;
cout<< "a=" <<a<< "," << "b=" <<b<<endl;
cout<< "a+b =" <<add (a,b) <<endl;

Math math;
cout<< "a*b =" <<math. Multiply (a,b) <<endl;

return 0;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.