27

How do I write a DLL file in C?

I was looking online, but I always get tutorials for C++, not C. I want to write my first DLL file in C. How can I do that? What would a short example be?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user1386966
  • 3,302
  • 13
  • 43
  • 72
  • Build as a Windows Dynamic Library project. – m0skit0 Nov 04 '12 at 13:22
  • That doesn't answer the question, but just a quick heads-up: unless you have very specific constraints you would rather write your application or library in C# on top of .Net. Your code would be more robust. Debug is easier. Less prone to memory leaks. Easier exception handling. You would gain in productivity. – Samuel Rossille Nov 04 '12 at 13:23
  • Im supposed to write it in C , just open a new project and write a really simple DLL, with any function I want (add \ mul \hello world..) but just can't understand how to do it :( – user1386966 Nov 04 '12 at 13:28
  • 2
    Whatever tutorial you follow for C++, you can do similar using C. Just do not use any C++ specific features (classes, overloading) etc. rather write C functions. – Rohan Nov 04 '12 at 14:10
  • Why don't you use an IDE that simplifies the process for you? like codeblocks, I believe codeblocks gives an example by default (codebase). –  Nov 04 '12 at 14:43
  • Possible duplicate of http://stackoverflow.com/q/9036859/577167 – skink Nov 04 '12 at 15:13

1 Answers1

35

Let's get you started on your first DLL:

  • Start Visual Studio .NET.
  • Go to menu File -> New -> Project.
  • Select Visual C++ Project, and from the Templates, select Win32 Project.
  • Give the name to your project. This will be the name of your final DLL file.
  • Press OK.
  • Select DLL from Application Type (In the Application Settings tab).
  • Check Empty Project and press Finish.

You need to attach an empty source file to the blank project:

  • Start Solution Explorer (if it’s not displayed).
  • Right click to the Source Files, Add -> Add New Item and then select C++ File and give the name to it.
  • Press Open.

In the opened window, enter the following code:

#include <stdio.h>
extern "C"
{
    __declspec(dllexport) void DisplayHelloFromMyDLL()
    {
        printf ("Hello DLL.\n");
    }
}
  • __declspec(dllexport) is an obligatory prefix which makes DLL functions available from an external application.

  • extern “C” (with braces, for scoping) shows that all code within brackets is available from “outside” the file. Although code will compile even without this statement, during runtime, you will get an error. (I leave this as an experiment for you).

Build this application and your DLL file is ready.

Refer to Walkthrough: Creating and Using a Dynamic Link Library for more information on how to do addition and stuff.

askmish
  • 6,464
  • 23
  • 42