Click to See Complete Forum and Search --> : calling "c" functions from c++


Kohinoor24
September 16th, 2002, 07:17 AM
I have a .h File as follows.I have got The dll & lib files concerning this file.I dont have the source files.
I have included the .h file to say that its plain 'C' code.
I want to call the 'c' function defined in the library from my c++ enviornment.
How is that possible.
I have included the library,but still its shoeing me Link Errors.

#if !defined(AFX_PJT_H__68E69803_22EA_11D2_838F_00A0243D3A7E__INCLUDED_)
#define AFX_PJT_H__68E69803_22EA_11D2_838F_00A0243D3A7E__INCLUDED_

#if _MSC_VER >= 1000
#pragma once
#endif
/* _MSC_VER >= 1000 */
#ifndef _GLOBALDEF
#define _GLOBALDEF
#endi
#ifdef M_UNIX
#define __stdcall
#endif

//Function

_GLOBALDEF int __stdcall pjtOpen(const char* filename, const char* stepid);

#endif

Thanks in advance

PaulWendt
September 16th, 2002, 09:11 AM
You have to use extern "C":

#if !defined(AFX_PJT_H__68E69803_22EA_11D2_838F_00A024
3D3A7E__INCLUDED_)
#define AFX_PJT_H__68E69803_22EA_11D2_838F_00A0243D3A7E__I
NCLUDED_

#if _MSC_VER >= 1000
#pragma once
#endif
/* _MSC_VER >= 1000 */
#ifndef _GLOBALDEF
#define _GLOBALDEF
#endi
#ifdef M_UNIX
#define __stdcall
#endif

//Function

#ifdef __cplusplus
extern "C"
{
#endif

_GLOBALDEF int __stdcall pjtOpen(const char* filename, const char* stepid);

#ifdef __cplusplus
}
#endif

#endif


Do the same thing around your function's definition.

--Paul

AnthonyMai
September 16th, 2002, 10:31 AM
Do the same thing around your function's definition.

--Paul



Wrong!!!

By its own definition, extern "C" is needed when you need to call a C function from a C++ source file. The definition of the C function certainly is located in a C source file, not a CPP file. Functions in a C file certainly uses C calling convention. There is no need to put an extern "C" there. If any thing, it is harmful to put extern "C" because the C compiler compiling the C file probably has no idea what it is.

If the "C" function you talked about was in a CPP file, then the default calling convension is C++, not C, and there is no need to put a extern "C" in either the header file or the source file.

The only situation I can think about, that requires both extern "C" in both the declaration and definition of a global function, is when you implement the function in a CPP file, but you want both CPP source file and C source file to be able to call it.

PaulWendt
September 16th, 2002, 10:59 AM
Mai's definitely right about this one. As soon as I thought about
it, I realized the error of my ways. Thank you for your correction,
AnthonyMai.

--Paul

jflegert
September 17th, 2002, 06:32 AM
Hello Kohinoor24,

Did you solve your problem?
How about trying (in your code):

extern "C" {
#include "the_header_file_from_the_library.h"
};

Good luck,
John Flegert

Kohinoor24
September 17th, 2002, 06:37 AM
thanks...