Thread: Windows 10 MinGW GCC Compile a program to DLL

  1. #1
    Registered User
    Join Date
    Sep 2018
    Posts
    21

    Windows 10 MinGW GCC Compile a program to DLL

    Hello all!
    I would like to use this article HOWTO Create and Deploy a Sample DLL using MinGW | MinGW
    but it's not clear for instance how to create DLL from C source using GCC instead of G++ that I will use in other languages programs on Windows. Could you provide any example?
    Thank you.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    37,596
    Just use that example, and remove any parts of the code which are specific to C++.
    The compile the result as instructed as a C program.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Sep 2018
    Posts
    21
    add.c
    Code:
    #include "add.h"
    int ADDCALL Add(int a, int b)
    {
      return (a + b);
    }
    add.h
    Code:
    #ifdef ADD_EXPORTS
        #define ADDAPI __declspec(dllexport)
      #else
        #define ADDAPI __declspec(dllimport)
      #endif
      /* Define calling convention in one place, for convenience. */
      #define ADDCALL __cdecl
    Command first
    gcc -c -DBUILDING_EXAMPLE_DLL add.c -D ADD_EXPORTS
    Command second
    gcc -shared -o add.dll add.o -Wl,--out-implib,libadd.dll
    Then, in C# caller
    Code:
    [DllImport("libadd.dll")]
    publicstaticexternintAdd (inta, intb);
    
    I've got an exception BadImageFormat when I'm trying to execute intsum=Add(1,2);

    What's going wrong?

  4. #4
    Registered User
    Join Date
    Sep 2018
    Posts
    21
    I'm using mingw 32-bit but mingw-w64 with -m64 gcc flag compilation were needed. It works.

  5. #5
    Registered User
    Join Date
    Sep 2018
    Posts
    21
    Finally,
    gcc -o add.dll -s -shared add.c -D ADD_EXPORTS -m64
    then
    [DllImport("add.dll")]
    works with x64 .Net Core app.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 0
    Last Post: 10-29-2011, 11:30 PM
  2. What do I need to use mingw in Windows
    By Joelito in forum A Brief History of Cprogramming.com
    Replies: 17
    Last Post: 01-13-2009, 02:36 AM
  3. Windows.h under MinGw
    By C_ntua in forum C Programming
    Replies: 2
    Last Post: 06-23-2008, 01:48 PM
  4. Can anyone using mingw compile this?
    By deoren in forum Linux Programming
    Replies: 4
    Last Post: 03-18-2003, 11:18 AM
  5. Replies: 2
    Last Post: 10-01-2001, 01:03 PM

Tags for this Thread