0

I am trying to create a .dll file which uses both c and c++ functions in visual studio. I have tried this so far,
create new project visual c++ -->windows Desktop wizard --> application type(.dll) and empty project.
and included the following files

cfunctions.h file

#include <stdio.h>
#if defined (WIN32)
#if defined(FUNCTIONS_STATIC)
#define FUNCTIONS_API
#else
#if defined(FUNCTIONS_EXPORTS)
#define FUNCTIONS_API __declspec(dllexport)
#else
#define FUNCTIONS_API __declspec(dllimport)
#endif
#endif
#else
#define FUNCTIONS_API
#endif
#ifdef __cplusplus
extern "C" {
#endif

FUNCTIONS_API double PowerOf2(double UserNumber);
FUNCTIONS_API double PowerOf3(double UserNumber);

#ifdef __cplusplus
}
#endif

cfunctions.c file

#define FUNCTIONS_EXPORTS
#include "cfunctions.h"

double PowerOf2(double UserNumber)
{
    return UserNumber * UserNumber;
}

double PowerOf3(double UserNumber)
{
    return UserNumber * UserNumber * UserNumber;
}

.cpp file

   #include <stdio.h>
    extern "C"
    {
       #include "cfunctions.h"
    }
    int main()
    {

        double p2 = 10.0;
        double p3 = 5.0;
        printf("The number %.2f to the power of 2 is %.2f. \n", p2, PowerOf2(p2));
        printf("The number %.2f to the power of 3 is %.2f. \n", p3, PowerOf3(p3));
        getchar();
        return 0;
    }

when i try to run the project it throws an error

unable to start program ..\xxx\project_name.dll
xxxx\project_name.dll is not a valid win 32 application

  • 3
    Looks like you are trying to execute the DLL. You need an .EXE that calls the DLL...it won't execute by itself. You probably should have a DLL project with the .c and .h file, and an .exe project with the .cpp file. You also don't need the extra `extern "C"` in the .cpp file. The header file contains the appropriate wrapper. – Mark Tolonen Feb 20 '18 at 18:31
  • You also are writing C code but compiling it as C++. Don't do that. Write either C++ code of rename the `.cpp` file into a `.c` file. – Pablo Feb 20 '18 at 18:41
  • @MarkTolonen yeah earlier i have tried the same(a DLL project with the .c and .h file, and an .exe project with the .cpp file), but the problem in my case is: I have a third party application which compiles my cpp file in to a dll file with help of visual studio.(a dll file is generated in the background and used for further process, a batch is scripted fr compilation). So it works fine in earlier case(where i provide the linker settings) but in the second case I don't know where to provide the linker settings so on running the application it gives me linking error. – Sai Krishna Feb 20 '18 at 20:38

0 Answers0