Error C2491 on C source with Visual studio 8 - c

i'm really noob in C. I just need to compile a ANSI C source to get a dll.
During compilation i get this error:
C2491: 'SelectML': definition of dllimport function not allowed
Where SelectML is a public function with this definition:
int CALLINGCONV SelectML(WORD fid, int nSlot)
{
WORD SW;
int x;
BYTE pSend[2];
pSend[0]=(BYTE)((fid&0xff00)>>8);
pSend[1]=(BYTE)(fid&0x00ff);
x=SendAPDUML(hCards[nSlot],APDU_SELECT,2,0,pSend,0,&SW);
if (x!=C_OK) return x;
if (SW!=0x9000) return SW;
return C_OK;
}
I'm sure the C source is good, maybe it is just a Visual Studio configuration...
This is another linked header:
#ifndef LIBSIAECARDT_H
#define LIBSIAECARDT_H
#ifdef __cplusplus
extern "C" {
#endif
#if !defined(USE_STDCALL)
#define USE_STDCALL 1
#endif
#ifdef _WIN32
# if USE_STDCALL == 1
# define CALLINGCONV_1 _stdcall
# else
# define CALLINGCONV_1
# endif
# if defined(LIBSIAE_EXPORTS)
# define LIBSIAEAPI __declspec(dllexport)
# else
# define LIBSIAEAPI __declspec(dllimport)
# endif
# define CALLINGCONV LIBSIAEAPI CALLINGCONV_1
#else // ! _WIN32
# define CALLINGCONV
# define LIBSIAEAPI
# define CALLINGCONV_1
typedef unsigned int UINT;
#endif // _WIN32

It's common to have a macro like CALLINGCONV conditionally defined as __declspec(dllimport) or __declspec(dllexport) so that the same header file can be used in the library source and in the code using the library. Your build should probably define something that makes it use dllexport. Check how CALLINGCONV is defined or (preferably) consult any build documentation that came with the code.

Quoted in MSDN says it all. Do not define the function. Declaration is good. What you are doing here is defining SelectML which for sure is generating your C2491 Error.

Here's an alternative. Stop using MSVC. They explicitly dropped support for anything after C90. Use an actual C compiler for C code.

Related

How can I find out without using AUTOCONF exactly what specifier (if any) is supported by a C compiler: inline, __inline__ or __inline?

Our project uses a lot of small one-line inline functions for simple arithmetical calculations. How can we find out exactly what inline specifier is used by user's C compiler: inline, __inline or __inline__?
We looked at how GLIB library does it. The fragment is given below:
/* inlining hassle. for compilers that don't allow the `inline' keyword,
* mostly because of strict ANSI C compliance or dumbness, we try to fall
* back to either `__inline__' or `__inline'.
* we define G_CAN_INLINE, if the compiler seems to be actually
* *capable* to do function inlining, in which case inline function bodys
* do make sense. we also define G_INLINE_FUNC to properly export the
* function prototypes if no inlining can be performed.
* we special case most of the stuff, so inline functions can have a normal
* implementation by defining G_INLINE_FUNC to extern and G_CAN_INLINE to 1.
*/
#ifndef G_INLINE_FUNC
# define G_CAN_INLINE 1
#endif
#ifdef G_HAVE_INLINE // compiler supports the __inline__ specifier
# if defined (__GNUC__) && defined (__STRICT_ANSI__)
# undef inline
# define inline __inline__
# endif
#else /* !G_HAVE_INLINE */
# undef inline
# if defined (G_HAVE___INLINE__)
# define inline __inline__
# else /* !inline && !__inline__ */
# if defined (G_HAVE___INLINE) // compiler supports the __inline specifier
# define inline __inline
# else /* !inline && !__inline__ && !__inline */
# define inline /* don't inline, then */
# ifndef G_INLINE_FUNC
# undef G_CAN_INLINE
# endif
# endif
# endif
#endif
#ifndef G_INLINE_FUNC
# ifdef __GNUC__
# ifdef __OPTIMIZE__
# define G_INLINE_FUNC extern inline
# else
# undef G_CAN_INLINE
# define G_INLINE_FUNC extern
# endif
# else /* !__GNUC__ */
# ifdef G_CAN_INLINE
# define G_INLINE_FUNC static inline
# else
# define G_INLINE_FUNC extern
# endif
# endif /* !__GNUC__ */
#endif /* !G_INLINE_FUNC */
They seem to set G_HAVE_INLINE and G_HAVE__INLINE_ in their very complicated configure file. Is there any way to do it in code without using autotools?
AC_C_INLINE, with this autoconf macro, you can use inline in all cases, provided you include config.h (usual name for the autoconf generated header).

Error compiling metismex in matlab r2013

I have downloaded and succesfully compiled metis 5.0.2 in a win7 x64 pc
and trying to compile metismex.
I compiled metis with Visual Studio 11 (2012) and using the same compiler from within matlab.
After a lot of experimentation with a ton of errors (mainly owed to paths issues from within the libraries) I have reached a point where I dont know how to proceed, since my knowledge on c and c++ is pretty basic.
So, here's the error :
../GKlib/mat_libs/.\stddef.h(16) : error C2054: expected '(' to follow '_SIZE_TYPE__'
../GKlib/mat_libs/.\stddef.h(19) : error C2085: '_WCHAR_TYPE__' : not in formal parameter list
I found out about the inline functions etc, but since the error is within a library and dont exactly know what I should be doing, here I am. So, the error code is produced here :
typedef __SIZE_TYPE__ size_t;
#ifndef __cplusplus
typedef __WCHAR_TYPE__ wchar_t;
#endif
any suggestions on what I should do without messing it up?
(in case I comment out wchar type, I also have the same error on prtdiff_type)
Thanks in advance
P.S: In case it is needed, here's the whole sttdef.h
/* Copyright 2012 The MathWorks, Inc. */
#ifndef _STDDEF_H
#define _STDDEF_H
#ifdef __cplusplus
extern "C" {
#endif
#ifdef __cplusplus
# define NULL (0)
#else
# define NULL ((void *)0)
#endif
typedef __SIZE_TYPE__ size_t;
#ifndef __cplusplus
typedef __WCHAR_TYPE__ wchar_t;
#endif
typedef __PTRDIFF_TYPE__ ptrdiff_t;
#if (! defined(__cplusplus)) || (! defined(PST_GNU))
# define offsetof(type, field) ((size_t) &((type *)0)->field)
#else
# define offsetof(type, field) \
(__offsetof__(reinterpret_cast<size_t> \
(&reinterpret_cast<const volatile char &> \
(static_cast<type *>(0)->field))))
#endif
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* _STDDEF_H *
/
Here is a walk-through of what I did. I'm running R2014a with VS2013 on Win8.1 x64.
1) First we compile metis:
Download and extract metis-5.1.0 to some location, say C:\metis-5.1.0
Edit C:\metis-5.1.0\include\metis.h and set #define IDXTYPEWIDTH 64 (for x64 architecture)
Next we generate Visual Studio projects using CMake:
> cd C:\metis-5.1.0
> vsgen -G "Visual Studio 12 2013 Win64"
Before we build the solution, we need to fix a few things first. Some header files are unnecessarily redefining rint function for MSVC (metisbin.h, metislib.h, and gk_arch.h). Remove such lines:
#ifdef __MSC__ /* MSC does not have rint() function */
#define rint(x) ((int)((x)+0.5))
/* MSC does not have INFINITY defined */
#ifndef INFINITY
#define INFINITY FLT_MAX
#endif
#endif
Also in GKlib\gk_externs.h replace all occurrences of __thread with __declspec(thread)
Next open the solution file C:\metis-5.1.0\build\windows\METIS.sln in Visual Stduio, and build ALL_BUILD target (make sure "x64" in "Release" mode is selected).
We are mainly interested in the metis project. Its result should be stored in C:\metis-5.1.0\build\windows\libmetis\Release\metis.lib (a static library).
2) Next we build the MEX-function:
Download metismex and extract it to a folder inside the previous location (C:\metis-5.1.0\metismex-master)
Again we need to fix a few things: first rename metismex.c to metismex.cpp (the C++ compiler is much better than the C compiler in Visual Studio!). Next edit this file and replace: #include <strings.h> with #include <string.h>, and add the following code immediately after it:
#if defined(_WIN32) || defined(_WIN64)
#define snprintf _snprintf
#define vsnprintf _vsnprintf
#define strcasecmp _stricmp
#define strncasecmp _strnicmp
#endif
Finally start MATLAB, and run the following command to compile the MEX-file:
>> cd('C:\metis-5.1.0\metismex-master')
>> mex -O -largeArrayDims -DWIN32 -DMSC -DUSE_GKREGEX -I../GKlib -I../include -I../libmetis metismex.cpp ../build/windows/libmetis/Release/metis.lib
You should now have the final metismex.mexw64
I should say that I know nothing about the library, so I cannot guarantee it gives correct results after all the above modifications. I'm just showing how to get it to compile. The code was written with Linux/OSX in mind, and relies on many POSIX features not intended for Windows. Also the whole 32 vs. 64 bit is a bit messy...

weird c function syntax

I know my C up to this point. I was looking at the source files of PHP I downloaded, and I saw this strange syntax:
PHPAPI int php_printf(const char *format, ...)
{
// code...
}
What does the PHPAPI do before the return type int? I've tried searching all over and I can't understand what this means. Is it a second return type? It can't be because the function does return an int. Maybe it extends to some other struct declared in a header file?
The hard way:
Go to the makefile and add in the line that compiles the sources: -E, by doing so you will see the source cose after the preprocessing phase.
The easy way:
Search all the project for PHPAPI:
find it in php.h:
#ifdef PHP_WIN32
#include "win95nt.h"
# ifdef PHP_EXPORTS
# define PHPAPI __declspec(dllexport)
# else
# define PHPAPI __declspec(dllimport)
# endif
#define PHP_DIR_SEPARATOR '\\'
#else
#define PHPAPI
#define THREAD_LS
#define PHP_DIR_SEPARATOR '/'
#endif
Now what you need to know is what is __declspec(dllexport) and what is __declspec(dllimport)
In the SO thread- What is __declspec and when do I need to use it?
see Alexander Gessler answer:
The canonical examples are __declspec(dllimport) and
__declspec(dllexport), which instruct the linker to import and
export (respectively) a symbol from or to a DLL.
// header
__declspec(dllimport) void foo();
// code - this calls foo() somewhere in a DLL
foo();
(__declspec(..) just wraps up Microsoft's specific stuff - to
achieve compatibility, one would usually wrap it away with macros)

Serial- / Socket IO and GCC nothrow attribute

I have functions which abstract serial- and socket IO (Linux / Windows) implemented in C.
All of them are marked as extern "C" because they may get called from C++ as well.
Is it safe to use __attribute__((__nothrow__)) (or MinGW Macro __MINGW_NOTHROW) here / can i assume no exceptions are thrown?
Called functions - Sockets:
(not all additions for WinSock listed)
socket
connect
send / recv
close (closesocket on Windows)
sendto / recvfrom
Called functions - Serial:
Since serial IO code differs to much between windows / linux not all are listed here
Linux (GNU)
open
tcgetattr
read / write
close
Windows (MinGW)
CreateFile
GetCommState / SetCommTimeouts
ReadFile / WriteFile
CloseHandle
Since ANSI C has no exceptions (please correct me if I'm wrong) they won't be thrown, but how about GCC extensions and OS API calls?
Documentation: http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html (see nothrow).
C
GNU C (Linux) uses __THROW macro instead of __MINGW_NOTHROW.
While the MinGW one is __nothrow__ attribute only, __THROW contains __leaf__ attribute too.
C++
If you use C++, __THROW has another meaning: throw() - indicating that no exception is thrown (analog to __nothrow__; but defined in the C++ standard).
So it depends on whether you compile with C or C++, not on what you call the functions from (GNU C / C++ only!).
Example:
void f() __THROW;
Treated as ...
GNU C:
void f() __attribute__((__nothrow__, __leaf__))
GNU C++:
void f() throw()
Functions1) which are cancellation points, therefore not marked with
__THROW:
open()
read()
write()
close()
connect()
send()
recv()
close()
sendto()
recvfrom()
Functions1) marked with __THROW:
tcgetattr()
socket()
At least, these are save to __nothrow__.
In contrast, MinGW doesn't differ C from C++; in both cases the attribute is set.
Using example from above, __nothrow__ is set on C and C++:
void f() __attribute((__nothrow__))
Functions1) not marked with __MINGW_NOTHROW:
socket()
connect()
send()
recv()
closesocket()
sendto()
recvfrom()
CreateFile()
GetCommState()
SetCommTimeouts()
ReadFile()
WriteFile()
CloseHandle()
To make it short: none!
Compatibility
With C
C language code that is expecting to interoperate with C++ should be
compiled with -fexceptions. This will make debugging a C language
function called as part of C++-induced stack unwinding possible.
In particular, unwinding into a frame with no exception handling data
will cause a runtime abort. If the unwinder runs out of unwind info
before it finds a handler, std::terminate() is called.
Please note that most development environments should take care of
getting these details right. For GNU systems, all appropriate parts of
the GNU C library are already compiled with -fexceptions.
( source: http://gcc.gnu.org/onlinedocs/libstdc++/manual/using_exceptions.html )
So compiling with -fexceptions and there's no need for equivalent attribute. If you only can mark specific functions you have to / should use __nothrow__.
But while using __nothrow__ attribute looks save only on GNU C++, and some functions of GNU C on Linux, it's not that clear on Windows.
Addendum:
To avoid some parts of this problem, i've written a macro similar to __THROW but usable on MinGW too:
#if defined __GNUC__
#ifndef __THROW
#ifdef __cplusplus
#define __THROW throw()
#else
#define __THROW __attribute__((__nothrow__))
#endif
#endif
#else
#define __THROW
#endif
Note: __leaf__ is not included.
1) Talking only about those which are listed on my question.
take care of gcc version, nothrow has been introduced with gcc 3.3!
you can port __THROW from sys/cdefs.h to mingw:
/* skip this entire part on linux (= glibc available)*/
#if defined __GNUC__ && !defined __linux__
/********* port __GNUC_PREREQ macro to mingw *********/
# if !defined __GNUC_PREREQ
# if !defined __MINGW_H
# include <_mingw.h>
# define __GNUC_PREREQ(major, minor) __MINGW_GNUC_PREREQ(major, minor)
# else
# if defined (__GNUC_MINOR__)
# define __GNUC_PREREQ(major, minor) __GNUC__ > (major) || (__GNUC__ == (major) && __GNUC_MINOR__ >= (minor)))
# else
# define __GNUC_PREREQ(major, minor) 0
# endif
# endif
#endif /* __GNUC_PREREQ */
/********* from gnu c blirary *********/
/* All functions, except those with callbacks or those that
synchronize memory, are leaf functions. */
# if __GNUC_PREREQ (4, 6) && !defined _LIBC
# define __LEAF , __leaf__
# define __LEAF_ATTR __attribute__ ((__leaf__))
# else
# define __LEAF
# define __LEAF_ATTR
# endif
/* GCC can always grok prototypes. For C++ programs we add throw()
to help it optimize the function calls. But this works only with
gcc 2.8.x and egcs. For gcc 3.2 and up we even mark C functions
as non-throwing using a function attribute since programs can use
the -fexceptions options for C code as well. */
# if !defined __cplusplus && __GNUC_PREREQ (3, 3)
# define __THROW __attribute__ ((__nothrow__ __LEAF))
# define __THROWNL __attribute__ ((__nothrow__))
# define __NTH(fct) __attribute__ ((__nothrow__ __LEAF)) fct
# else
# if defined __cplusplus && __GNUC_PREREQ (2,8)
# define __THROW throw ()
# define __THROWNL throw ()
# define __NTH(fct) __LEAF_ATTR fct throw ()
# else
# define __THROW
# define __THROWNL
# define __NTH(fct) fct
# endif
# endif
#else /* Not GCC. */
# define __inline /* No inline functions. */
# define __THROW
# define __THROWNL
# define __NTH(fct) fct
#endif /* GCC. */
see glibc - sys/cdefs.h for full code.
edit: __GNUC_PREREQ can be replaced with __MINGW_GNUC_PREREQ(major, minor), then you don't have to redifine it as above.

C2059 syntax error using declspec macro for one function; compiles fine without it

I've making a shared library (cross-platform), but when trying to compile the Windows build I'm encountering the error:
secure_string.h(43) : error C2059: syntax error : 'type'
This is in regards to the SECURESTRING_API macro. It doesn't complain about the two usages in strlcpy and strlcat, but when trying to use it for 'str_from_last' it generates the above error.
If I remove it, it compiles fine, but the function then isn't exported from the DLL, making it quite useless!
A Google search has yielded no (relevant) results; has anyone encountered this before? I've tested on both Visual Studio 2008 and 2010, and the result is identical. The source file includes string.h and then this file - nothing else.
Header file:
#ifndef SECURE_STRING_H
#define SECURE_STRING_H
/* Provide MS Builds with import/export functionality
* BUILD_SECURE_STRING should be added to project preprocessor macros */
#if _WIN32
# if defined(BUILD_SECURE_STRING)
# define SECURESTRING_API __declspec(dllexport)
# else
# define SECURESTRING_API __declspec(dllimport)
# endif
#else
# define SECURESTRING_API
#endif
/* Windows on the whole, and glibc do not have/support strlc[at|py]
* This will almost certainly need revision for proper cross-platform checks */
#if _WIN32 || __GLIBC__ || !defined(HAVE_STRLCPY)
size_t SECURESTRING_API strlcat(char* dst, const char* src, size_t size);
size_t SECURESTRING_API strlcpy(char* dst, const char* src, size_t size);
#else
# define HAVE_STRLCPY 1
#endif
/* In case the active project has yet to include headers for 'BOOL' */
#ifndef BOOL
# define BOOL int
# define TRUE 1
# define FALSE 0
#endif
/*
| Locates 'search' within 'source', and if found, returns either the
| character itself, or the character after it if 'return_from_after_found'
| is TRUE.
| If it is not found, or any parameter is invalid, a NULL pointer is returned.
*/
char* SECURESTRING_API
str_from_last(char* source,
char search,
BOOL return_from_after_found);
#endif /* SECURE_STRING_H */
#if _WIN32
Are you sure you're entering this? I would:
#if defined(WIN32)
EDIT: That looks OK but this I think is it:
move the SECURESTRING_API before the return type (char*):
SECURESTRING_API char*
With this change your code compiles for me under VS2010 and MSDN confirms that is the required order:
The decl-specifier-seq should contain, among other things, a base type
(e.g. int, float, a typedef, or a class name), a storage class (e.g.
static, extern), or the __declspec extension. The init-declarator-list
should contain, among other things, the pointer part of
declarations.

Resources