Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C code compiles as C++, but not as C [duplicate]

Possible Duplicate:
Convert some code from C++ to C

I've got some code that appears to be straight C. When I tell the compiler (I'm using Visual Studio 2008 Express) to compile it as c++, it compiles and links fine. When I try to compile it as C, though, it throws this error:

1>InpoutTest.obj : error LNK2019: unresolved external symbol _Out32@8 referenced in function _main
1>InpoutTest.obj : error LNK2019: unresolved external symbol _Inp32@4 referenced in function _main

The code reads from and writes to the parallel port, using Inpout.dll. I have both Inpout.lib and Inpout.dll. Here's the code:

// InpoutTest.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "stdio.h"
#include "string.h"
#include "stdlib.h"
/* ----Prototypes of Inp and Outp--- */

short _stdcall Inp32(short PortAddress);
void _stdcall Out32(short PortAddress, short data);

/*--------------------------------*/

int main(int argc, char* argv[])
{

 int data;

 if(argc<3)
 {
  //too few command line arguments, show usage
  printf("Error : too few arguments\n\n***** Usage *****\n\nInpoutTest read <ADDRESS> \nor \nInpoutTest write <ADDRESS> <DATA>\n\n\n\n\n");
 } 
 else if(!strcmp(argv[1],"read"))
 {

  data = Inp32(atoi(argv[2]));

  printf("Data read from address %s is %d \n\n\n\n",argv[2],data);

 }
 else if(!strcmp(argv[1],"write"))
 {
  if(argc<4)
  {
   printf("Error in arguments supplied");
   printf("\n***** Usage *****\n\nInpoutTest read <ADDRESS> \nor \nInpoutTest write <ADDRESS> <DATA>\n\n\n\n\n");
  }
  else
  {
  Out32(atoi(argv[2]),atoi(argv[3]));
  printf("data written to %s\n\n\n",argv[2]);
  }
 }



 return 0;
}

I previously asked this question, incorrectly, here.

Any help would be appreciated.

like image 603
Colin DeClue Avatar asked Dec 02 '22 05:12

Colin DeClue


1 Answers

You're trying to link to a C++ function, from C. That doesn't work due to name mangling- the linker doesn't know where to look for your function. If you want to call a C function from C++, you must mark it extern "C". C does not support extern "C++"- as far as I know. One of the other answers says there is. Alternatively, recompile it's source code as C.

Edit: Why ever would you compile as C if you could compile as C++, anyway?

like image 84
Puppy Avatar answered Dec 25 '22 12:12

Puppy