Now that we have learned how to use the Visual Studio IDE and how to
create command-line and Windows applications, we will learn how to
write code so that it can be used by multiple applications. One way
to do this is to create a library that contains related classes and
algorithms. For example, Visual C++ is included with many libraries
that any C or C++ application can use, such as the
C Run-Time Library and the
Standard C++ Library. Without these libraries, there would be no
standard way for a C or C++ application to write to the console or
determine the current date and time.
Every C or C++ application
will likely use one of the previously mentioned libraries. You can
also create your own libraries of classes and algorithms that any
application can use. With Visual C++, you can create three kinds of
libraries:
Dynamic link libraries (DLLs).
Static libraries.
Managed assemblies.
In general, if you are creating a library that can be used by
native C++ code, you will create either a dynamic link library or a
static library. For more information about how to determine which
type of library to create, see
DLLs. If you are creating a library that can be used by C++/CLI
or any other .NET language such as C# or Visual Basic, you will
create a managed assembly.
In this section, we will create a simple library of standard math
operations such as addition and multiplication, and we will show how
applications can use this library.
Prerequisites
These topics assume that you understand the fundamentals
of the C++ language.
In
This Section
Creating and Using a Dynamic Link Library (C++)
Creating and Using a Static Library (C++)
Creating and Using a Managed Assembly (C++)
Creating and Using a Dynamic Link Library (C++)
The first type of library we will create is a dynamic link library
(DLL). Using DLLs is a great way to reuse code. Rather than
re-implementing the same routines in every program that you create,
you write them one time and reference them from applications that
need the functionality.
This walkthrough covers the following:
Creating a new dynamic link library (DLL) project.
Adding a class to the dynamic link library.
Creating an application that references the dynamic link
library.
Using the functionality from the class library in the
console application.
Running the application.
Prerequisites
This topic assumes that you understand the fundamentals
of the C++ language.
To create a new dynamic link library
(DLL) project
From the File menu, select
New and then Project�.
On the Project types pane, under
Visual C++, select
Win32.
On the Templates pane, select
Win32 Console Application.
Choose a name for the project, such as
MathFuncsDll, and type it in the Name
field. Choose a name for the solution, such as
DynamicLibrary, and type it in the
Solution Name field.
Click OK to start the Win32
application wizard. On the Overview page
of the Win32 Application Wizard dialog
box, click Next.
On the Application Settings page of
the Win32 Application Wizard, under
Application type, select
DLL if it is available or
Console application if
DLL is not available. Some versions of Visual Studio do
not support creating a DLL project by using wizards. You can
change this later to make your project compile into a DLL.
On the Application Settings page of
the Win32 Application Wizard, under
Additional options, select
Empty project.
Click Finish to create the project.
To add a class to the dynamic link
library
To create a header file for a new class, from the
Project menu, select
Add New Item�. The Add New Item
dialog box will be displayed. On the Categories
pane, under Visual C++, select
Code. On the Templates
pane, select Header File (.h). Choose a
name for the header file, such as
MathFuncsDll.h, and click Add. A
blank file will be displayed.
Add a simple class named MyMathFuncs
to do common mathematical operations, such as addition,
subtraction, multiplication, and division. The code should
resemble the following:
Copy Code
// MathFuncsDll.h
namespace MathFuncs
{
class MyMathFuncs
{
public:
// Returns a + b
static __declspec(dllexport) double Add(double a, double b);
// Returns a - b
static __declspec(dllexport) double Subtract(double a, double b);
// Returns a * b
static __declspec(dllexport) double Multiply(double a, double b);
// Returns a / b
// Throws DivideByZeroException if b is 0
static __declspec(dllexport) double Divide(double a, double b);
};
}
Note the __declspec(dllexport)
modifier in the method declarations in this code. These
modifiers enable the method to be exported by the DLL so that it
can be used by other applications. For more information, see
dllexport, dllimport.
To create a source file for a new class, from the
Project menu, select
Add New Item�. The Add New Item
dialog box will be displayed. On the Categories
pane, under Visual C++, select
Code. On the Templates
pane, select C++ File (.cpp). Choose a
name for the source file, such as
MathFuncsDll.cpp, and click Add.
A blank file will be displayed.
Implement the functionality for
MyMathFuncs in the source file. The code should resemble
the following:
Copy Code
// MathFuncsDll.cpp
// compile with: /EHsc /LD
#include "MathFuncsDll.h"
#include
using namespace std;
namespace MathFuncs
{
double MyMathFuncs::Add(double a, double b)
{
return a + b;
}
double MyMathFuncs::Subtract(double a, double b)
{
return a - b;
}
double MyMathFuncs::Multiply(double a, double b)
{
return a * b;
}
double MyMathFuncs::Divide(double a, double b)
{
if (b == 0)
{
throw new invalid_argument("b cannot be zero!");
}
return a / b;
}
}
To build the project into a DLL, from the
Project menu, select MathFuncsDllProperties�. On the left pane, under
Configuration Properties, select
General. On the right pane, change the
Configuration Type to
Dynamic Library (.dll). Click OK
to save the changes.
Note:
If you are building a project from the command
line, use the /LD compiler option to specify
that the output file should be a DLL. For more
information, see
/MD, /MT, /LD (Use Run-Time Library).
Compile the dynamic link library by selecting
Build Solution from the
Build menu. This creates a DLL that can be used by other
programs. For more information about DLLs, see
DLLs.
To create an application that references
the dynamic link library
To create an application that will reference and use the
dynamic link library that you just created, from the
File menu, select New
and then Project�.
On the Project types pane, under
Visual C++, select
Win32.
On the Templates pane, select
Win32 Console Application.
Choose a name for the project, such as
MyExecRefsDll, and type it in the Name
field. Next to Solution, select
Add to Solution from the drop down list.
This will add the new project to the same solution as the
dynamic link library.
Click OK to start the
Win32 Application Wizard. On the
Overview page of the
Win32 Application Wizard dialog box, click
Next.
On the Application Settings page of
the Win32 Application Wizard, under
Application type, select
Console application.
On the Application Settings page of
the Win32 Application Wizard, under
Additional options, clear the
Precompiled header check box.
Press Finish to create the project.
To use the functionality from the class
library in the console application
After you create a new console application, an empty program
is created for you. The name for the source file is the same as
the name that you chose for the project earlier. In this
example, it is named MyExecRefsDll.cpp.
To use the math routines that were created in the dynamic
link library, you must reference the library. To do this, select
References� from the
Project menu. On the Property Pages
dialog box, expand the Common Properties
node, select References, and then select
the Add New Reference� button. For more
information about the References� dialog
box, see
Framework and References, Common Properties,
Property Pages Dialog Box.
The Add Reference dialog box is
displayed. This dialog lists all the libraries that you can
reference. The Project tab lists all the
projects in the current solution and any libraries they contain.
On the Projects tab, select
MathFuncsDll. Then click
OK. For more information about the
Add Reference dialog box, see
Add Reference Dialog Box.
To reference the header files of the dynamic link library,
you must modify the include directories path. To do this, on the
Property Pages dialog box, expand the
Configuration Properties node, expand
the C/C++ node, and then select
General. Next to
Additional Include Directories, type the path of the
location of the MathFuncsDll.h header
file.
The executable does not load dynamic link libraries until
runtime. You must tell the system where to locate
MathFuncsDll.dll. You do so by using
the PATH environment variable. To do this, on the
Property Pages dialog box, expand the
Configuration Properties node and select
Debugging. Next to
Environment, type the following:
PATH=<path of MathFuncsDll.dll
file>, where <path
of MathFuncsDll.dll file> is
replaced with the actual location of
MathFuncsDll.dll. Click OK to
save all the changes.
Note:
If you want to run the executable from the
command line instead of from Visual Studio, you must
manually update the PATH environment variable
from the command prompt as follows:
set PATH=%PATH%;<path of
MathFuncsDll.dll file>,
where
MathFuncsDll.dll file> is replaced with the
actual location of
MathFuncsDll.dll.
You can now use the MyMathFuncs
class in this application. Replace the contents of
MyExecRefsDll.cpp with the following
code:
Copy Code
// MyExecRefsDll.cpp
// compile with: /EHsc /link MathFuncsDll.lib
#include
#include "MathFuncsDll.h"
using namespace std;
int main()
{
double a = 7.4;
int b = 99;
cout << "a + b = " <<
MathFuncs::MyMathFuncs::Add(a, b) << endl;
cout << "a - b = " <<
MathFuncs::MyMathFuncs::Subtract(a, b) << endl;
cout << "a * b = " <<
MathFuncs::MyMathFuncs::Multiply(a, b) << endl;
cout << "a / b = " <<
MathFuncs::MyMathFuncs::Divide(a, b) << endl;
return 0;
}
Build the executable by selecting Build
Solution from the Build menu.
To run the application
Make sure MyExecRefsDll is
selected as the default project. In the
Solution Explorer, select
MyExecRefsDll, and then select Set As
StartUp Project from the Project
menu.
To run the project, select Start Without
Debugging from the Debug menu.
The output should resemble this:
Copy Code
a + b = 106.4
a - b = -91.6
a * b = 732.6
a / b = 0.0747475
Creating and Using a Static Library (C++)
The next type of library we will create is a
static library (LIB). Using static libraries is
a great way to reuse code. Rather than
re-implementing the same routines in every
program that you create, you write them one time
and reference them from applications that need
the functionality.
This walkthrough covers the
following:
Creating a new static library project.
Adding a class to the static library.
Creating an application that references
the static library.
Using the functionality from the static
library in the console application.
Running the application.
Prerequisites
This topic assumes that you
understand the fundamentals of the C++
language.
To create a new
static library project
From the File
menu, select New and
then Project�.
On the Project types
pane, under Visual C++,
select Win32.
On the Templates
pane, select Win32 Console
Application.
Choose a name for the project, such as
MathFuncsLib, and
enter it in the Name
field. Choose a name for the solution, such
as StaticLibrary,
and enter it in the
Solution Name field.
Press OK to
start the Win32 application wizard. On the
Overview page of the
Win32 Application Wizard
dialog box, press Next.
On the Application
Settings page of the
Win32 Application Wizard, under
Application type,
select Static library.
On the Application
Settings page of the
Win32 Application Wizard, under
Additional options,
clear the Precompiled
header check box.
Press Finish to
create the project.
To add a class to
the static library
To create a header file for a new class,
from the Project
menu, select Add New Item�.
The Add New Item
dialog box will be displayed. From the
Categories pane,
under Visual C++,
select Code. From
the Templates pane,
select Header File (.h).
Choose a name for the header file, such as
MathFuncsLib.h,
and press Add. A
blank file will be displayed.
Add a simple class named
MyMathFuncs to do
common mathematical operations, such as
addition, subtraction, multiplication, and
division. The code should resemble the
following:
Copy Code
// MathFuncsLib.h
namespace MathFuncs
{
class MyMathFuncs
{
public:
// Returns a + b
static double Add(double a, double b);
// Returns a - b
static double Subtract(double a, double b);
// Returns a * b
static double Multiply(double a, double b);
// Returns a / b
// Throws DivideByZeroException if b is 0
static double Divide(double a, double b);
};
}
To create a source file for a new class,
from the Project
menu, select Add New Item�.
The Add New Item
dialog box will be displayed. From the
Categories pane,
under Visual C++,
select Code. From
the Templates pane,
select C++ File (.cpp).
Choose a name for the source file, such as
MathFuncsLib.cpp,
and press Add. A
blank file will be displayed.
Implement the functionality for
MyMathFuncs in
the source file. The code should resemble
the following:
Copy Code
// MathFuncsLib.cpp
// compile with: /c /EHsc
// post-build command: lib MathFuncsLib.obj
#include "MathFuncsLib.h"
#include
using namespace std;
namespace MathFuncs
{
double MyMathFuncs::Add(double a, double b)
{
return a + b;
}
double MyMathFuncs::Subtract(double a, double b)
{
return a - b;
}
double MyMathFuncs::Multiply(double a, double b)
{
return a * b;
}
double MyMathFuncs::Divide(double a, double b)
{
if (b == 0)
{
throw new invalid_argument("b cannot be zero!");
}
return a / b;
}
}
To build the project into a static
library, from the Project
menu, select
MathFuncsLib
Properties�. On the left pane, under
Configuration Properties,
select General. On
the right pane, change the
Configuration Type to
Static Library (.lib).
Press OK to save the
changes.
Note:
When you build from the
command line, you must build the
program in two steps. First,
compile the code by using
Cl.exe with the /c
compiler option (cl
/c /EHsc MathFuncsLib.cpp).
This will create an object file
that is named
MathFuncsLib.obj. For
more information, see
/c (Compile Without Linking).
Second, link the code by using
the Library Manager Lib.exe
(lib
MathFuncsLib.obj). This
will create the static library
MathFuncsLib.lib. For
more information about the
Library Manager, see
LIB Reference.
Compile the static library by selecting
Build Solution from
the Build menu. This
creates a static library that can be used by
other programs.
To create an
application that references the static library
To create an application that will
reference and use the static library that
was just created, from the
File menu, select
New and then
Project�.
On the Project types
pane, under Visual C++,
select Win32.
On the Templates
pane, select Win32 Console
Application.
Choose a name for the project, such as
MyExecRefsLib,
and type it in the Name
field. Next to Solution,
select Add to Solution
from the drop down list. This will add the
new project to the same solution as the
static library.
Press OK to
start the Win32 Application
Wizard. On the
Overview page of the
Win32 Application Wizard dialog box,
press Next.
on the Application
Settings page of the
Win32 Application Wizard, under
Application type,
select Console application.
On the Application
Settings page of the
Win32 Application Wizard, under
Additional options,
clear Precompiled header.
Press Finish to
create the project.
To use the
functionality from the static library in the console
application
After you create a new console
application, the wizard creates an empty
program for you. The name for the source
file will be the same as the name that you
chose for the project earlier. In this
example, it is named
MyExecRefsLib.cpp.
To use the math routines that you
created in the static library, you must
reference it. To do this, select
References� from the
Project menu. From
the Property Pages
dialog box, expand the
Common Properties node and select
References. Then
select the Add New
Reference� button. For more
information about the
References� dialog box, see
Framework and References, Common Properties,
Property Pages Dialog Box.
The Add Reference
dialog box is displayed. This dialog box
lists all the libraries that you can
reference. The Project
tab lists all the projects in the current
solution and any libraries they contain. On
the Projects tab,
select MathFuncsLib.
Then select OK. For
more information about the
Add Reference dialog box, see
Add Reference Dialog Box.
To reference the header files of the
static library, you must modify the include
directories path. To do this, in the
Property Pages
dialog box, expand the
Configuration Properties node, expand
the C/C++ node, and
then select General.
Next to Additional Include
Directories, type the path of the
location of the
MathFuncsLib.h header file.
You can now use the
MyMathFuncs class in this
application. Replace the contents of
MyExecRefsLib.cpp
with the following code:
Copy Code
// MyExecRefsLib.cpp
// compile with: /EHsc /link MathFuncsLib.lib
#include
#include "MathFuncsLib.h"
using namespace std;
int main()
{
double a = 7.4;
int b = 99;
cout << "a + b = " <<
MathFuncs::MyMathFuncs::Add(a, b) << endl;
cout << "a - b = " <<
MathFuncs::MyMathFuncs::Subtract(a, b) << endl;
cout << "a * b = " <<
MathFuncs::MyMathFuncs::Multiply(a, b) << endl;
cout << "a / b = " <<
MathFuncs::MyMathFuncs::Divide(a, b) << endl;
return 0;
}
Build the executable by selecting
Build Solution from
the Build menu.
To run the
application
Make sure
MyExecRefsLib is selected as the
default project. In the
Solution Explorer, select
MyExecRefsLib,
and then select Set As
StartUp Project from the
Project menu.
To run the project, select
Start Without Debugging
from the Debug menu.
The output should resemble this:
Copy Code
a + b = 106.4
a - b = -91.6
a * b = 732.6
a / b = 0.0747475
Creating and Using a Managed Assembly (C++)
The next type of library that we will create is
a managed assembly. Using managed assemblies is
a great way to reuse code. Rather than
re-implementing the same routines in every
program that you create, you write them once and
reference them from applications that need the
functionality.
This walkthrough covers the
following:
Creating a new class library project.
Adding a class to the class library.
Creating an application that references
the class library.
Using the functionality from the class
library in the console application.
Running the application.
Prerequisites
This topic assumes that you
understand the fundamentals of the C++
language.
To create a new
class library project
From the File
menu, select New and
then select Project�.
On the Project types
pane, under Visual C++,
select CLR. This
creates a project that targets the common
language runtime.
On the Templates
pane, select Class Library.
Choose a name for the project, such as
MathFuncsAssembly,
and type it in the Name
field. Choose a name for the solution, such
as ManagedAssemblies,
and type it in the Solution
Name field.
Press OK to
create the project.
By default, when new projects are
created, they are set up to use precompiled
headers. To disable precompiled header,
select Properties
from the Project
menu. Expand the
Configuration Properties node, expand
the C/C++ node, and
then select Precompiled
Headers. From the dropdown list next
to Create/Use Precompiled
Header, select Not
Using Precompiled Header. Press
OK to save these
changes. For more information on precompiled
headers, see
Creating Precompiled Header Files.
To add a class to
the class library
After you create a new CLR Class
Library, the wizard generates a simple class
for you. The names for the header file and
source file will be the same as the name you
chose for the project earlier. In this
example, they are named
MathFuncsAssembly.h and
MathFuncsAssembly.cpp.
Replace the existing code in
MathFuncsAssembly.h
with a simple class that is named
MyMathFuncsAssembly
to do common mathematical operations, such
as addition, subtraction, multiplication,
and division. The code should resemble the
following:
Copy Code
// MathFuncsAssembly.h
using namespace System;
namespace MathFuncs
{
public ref class MyMathFuncs
{
public:
// Returns a + b
static double Add(double a, double b);
// Returns a - b
static double Subtract(double a, double b);
// Returns a * b
static double Multiply(double a, double b);
// Returns a / b
// Throws DivideByZeroException if b is 0
static double Divide(double a, double b);
};
}
Implement the functionality for
MyMathFuncs in
the source file. The code should resemble
the following:
Copy Code
// MathFuncsAssembly.cpp
// compile with: /clr /LD
#include "MathFuncsAssembly.h"
namespace MathFuncs
{
double MyMathFuncs::Add(double a, double b)
{
return a + b;
}
double MyMathFuncs::Subtract(double a, double b)
{
return a - b;
}
double MyMathFuncs::Multiply(double a, double b)
{
return a * b;
}
double MyMathFuncs::Divide(double a, double b)
{
if (b == 0)
{
throw gcnew DivideByZeroException("b cannot be zero!");
}
return a / b;
}
}
Compile the class library by selecting
Build Solution from
the Build menu. This
creates a dynamic link library (DLL) that
can be used by other programs. For more
information on DLLs, see
DLLs.
To create an
application that references the class library
To create an application that will
reference and use the class library that you
just created, from the File
menu, select New and
then select Project�.
On the Project types
pane, under Visual C++,
select CLR. This
creates a project that targets the Common
Language Runtime.
On the Templates
pane, select CLR Console
Application.
Choose a name for the project, such as
MyExecRefsAssembly,
and type it in the Name
field. Next to Solution,
select Add to Solution
from the drop down list. This will add the
new project to the same solution as the
class library.
Press OK to
create the project.
By default, when new projects are
created, they are set up to use precompiled
headers. To disable precompiled header,
select Properties
from the Project
menu. Expand the
Configuration Properties node, expand
the C/C++ node, and
then select Precompiled
Headers. From the dropdown list next
to Create/Use Precompiled
Header, select Not
Using Precompiled Header. Press
OK to save these
changes. For more information on precompiled
headers, see
Creating Precompiled Header Files.
To use the
functionality from the class library in the console
application
After you create a new CLR Console
Application, a program is created for you
that simply writes "Hello World" to the
console. The name for the source file will
be the same as the name you chose for the
project above. In this example, it is named
MyExecRefsAssembly.cpp.
To use the math routines that were
created in the class library, you must
reference it. To do this, select
References� from the
Project menu. On the
Property Pages
dialog box, expand the
Common Properties node and select
References, and then
select the Add New
Reference� button. For more
information about the
References� dialog, see
Framework and References, Common Properties,
Property Pages Dialog Box.
The Add Reference
dialog is displayed. This dialog lists all
the libraries that you can reference. The
.NET tab lists the
libraries that are included with the .NET
Framework. The COM
tab lists all the COM components on your
computer. The Project
tab lists all the projects in the current
solution and any libraries they contain. On
the Projects tab,
select MathFuncsAssembly
and then click OK.
For more information about the
Add Reference
dialog, see
Add Reference Dialog Box.
Note:
You can reference an
assembly directly from the
source file by including the
#using
directive, as in
#using
.
For more information about this
directive, see
The #using Directive.
You can now use the
MyMathFuncs class in this
application. In
MyExecRefsAssembly.cpp, replace the
contents of the file function with the
following code:
Copy Code
// MyExecRefsAssembly.cpp
// compile with: /clr /FUMathFuncsAssembly.dll
using namespace System;
int main(array ^args)
{
double a = 7.4;
int b = 99;
Console::WriteLine("a + b = {0}",
MathFuncs::MyMathFuncs::Add(a, b));
Console::WriteLine("a - b = {0}",
MathFuncs::MyMathFuncs::Subtract(a, b));
Console::WriteLine("a * b = {0}",
MathFuncs::MyMathFuncs::Multiply(a, b));
Console::WriteLine("a / b = {0}",
MathFuncs::MyMathFuncs::Divide(a, b));
return 0;
}
Build the executable by selecting
Build Solution from
the Build menu.
To run the
application
Make sure
MyExecRefsAssembly is selected as the
default project. From the
Solution Explorer, select
MyExecRefsAssembly,
and then select Set As
StartUp Project from the
Project menu.
To run the project, select
Start Without Debugging
from the Debug menu.
The output should look like this:
Copy Code
a + b = 106.4
a - b = -91.6
a * b = 732.6
a / b = 0.0747474747474748