- Remove From My Forums
-
Question
-
Hi,
I’m migrating a Win 32 project written in Visual C++ 5.0 to Visual Studio 2012. I get the below error message on building the application.
Error C2059: syntax error : ‘_ declspec(dllexport)’
Clicking on the Error messages it points to the code highlighted in bold.
/************************************************************************** * * * Public Function Prototypes * * * **************************************************************************/ #pragma once #ifdef __EXPORTING #define EXPORT_FN __declspec (dllexport) WINAPI #define C_EXPORT_FN __declspec (dllexport) _cdecl #else #define EXPORT_FN __declspec (dllimport) WINAPI #define C_EXPORT_FN __declspec (dllimport) _cdecl #endif double EXPORT_FN CrtRoundDouble (double dblNumber, USHORT usPrecision); /*+-----------------------------------------------------------------------+ | | | Utility Funcions | | | +-----------------------------------------------------------------------+*/ char* EXPORT_FN Get_LogFile(void); char* EXPORT_FN Get_LogFile2(void); char* EXPORT_FN Get_SQLFile(void); char* EXPORT_FN Get_WSFile(void); char* EXPORT_FN Set_LogFile(char *); char* EXPORT_FN Set_LogFile2(char *); char* EXPORT_FN Set_SQLFile(char *); char* EXPORT_FN Set_WSFile(char *); char* EXPORT_FN Set_Path(char *path); char* EXPORT_FN Get_Path(void); char* EXPORT_FN Get_Pwd(int index);
The above error message repeats for all the code in bold. I could not understand where the error is, could anyone help me to fix this error, it does not look like a syntax error though. Is it a migration error, as the same set of code works fine in vc++
5.0 without any issues?I also get the following Errors along with the above mentioned error:
Error C2143: syntax error: missing ‘;’ before ‘{‘
Error C2447: ‘{‘ missing function header (old-style formal list?)
Clicking on the error, it points to the following code. (get_Path is one of the utility functions mentioned in the code snippet above)
/* The following two function sets and gets the path*/
char* EXPORT_FN Get_Path(void) {
return &Path[0];
}
Thanks for any help!
-
Edited by
Tuesday, May 7, 2013 9:43 AM
-
Edited by
Answers
-
On 5/7/2013 4:13 AM, suj1234 wrote:
#ifdef __EXPORTING
#define EXPORT_FN __declspec (dllexport) WINAPI
#define C_EXPORT_FN __declspec (dllexport) _cdecl
#else
#define EXPORT_FN __declspec (dllimport) WINAPI
#define C_EXPORT_FN __declspec (dllimport) _cdecl
#endif
char* EXPORT_FN Get_LogFile(void);The syntax doesn’t allow __declspec where you have it (see
http://msdn.microsoft.com/en-us/library/dabb5z75.aspx , second example from the bottom). It should be one of__declspec(dllexport) char* Get_LogFile(void); char __declspec(dllexport) * Get_LogFile(void); PCHAR __declspec(dllexport) Get_LogFile(void);
Only the last version works if you want to keep __declspec and __stdcall (or __cdecl) together. Normally, they are separated into individual macros. For example, this is the declaration in a Windows header:
WINBASEAPI BOOL WINAPI CloseHandle( _In_ HANDLE hObject);
WINBASEAPI is a macro that expands to __declspec(dllimport) or nothing (and, presumably, to __declspec(dllexport) in the configuration used to actually build Windows from sources), while WINAPI expands to __stdcall. One goes before the return type, the other
after.
Igor Tandetnik
-
Proposed as answer by
Renjith V Ramachandran
Tuesday, May 7, 2013 1:55 PM -
Marked as answer by
suje
Wednesday, May 8, 2013 7:15 AM
-
Proposed as answer by
I’ve got a DLL that I’ve created as a C++ Win32 application. To prevent name mangling in my DLL, I have used the EXPORT definition defined below:
#ifndef EXPORT
#define EXPORT extern "C" __declspec(dllexport)
#endif
EXPORT int _stdcall SteadyFor(double Par[], double Inlet[], double Outlet[]);
To get this code to compile, I had to go into the project’s Properties and set the C/C++ Calling Convention
to __stdcall (/Gz) and set Compile As
to Compile as C++ Code (/TP).
This worked in Debug mode, but Release mode is throwing error C2059: syntax error: 'string'
on all of my EXPORT functions — even though I have configured the Release mode settings to be the same as the Debug settings.
How do I get Release Mode to compile?
Regards,
~Joe
(Developing under Visual Studio 2008 Professional)
EDIT:
A lot of comments about my #define, which does not appear to be causing any problems.
To eliminate the confusion, my header file has been rewritten as follows:
#ifndef coilmodel_h
#define coilmodel_h
extern "C" __declspec(dllexport) int _stdcall steadyFor(double Par[], double Inlet[], double Outlet[], char* FileIn, char* FileOut);
#endif
That is all of it.
The error is:
Description error C2059: syntax error: 'string'
File coilmodel.h
Line 4
Again, this error only appears in Release mode, not Debug mode.
Project is a C++ Win32 DLL application.
Содержание
- Ошибка компилятора C2059
- Name already in use
- cpp-docs / docs / error-messages / compiler-errors-1 / compiler-error-c2059.md
- Error c2059 syntax error declspec dllexport
- Лучший отвечающий
- Вопрос
- Ответы
- Error c2059 syntax error declspec dllexport
- Answered by:
- Question
- Answers
- All replies
Ошибка компилятора C2059
Синтаксическая ошибка: «token»
Маркер привел к синтаксической ошибке.
В следующем примере создается сообщение об ошибке для строки, которая объявляется j .
Чтобы определить причину ошибки, проверьте не только строку, указанную в сообщении об ошибке, но и строки над ней. Если проверка строк не дает каких либо сведений о проблеме, попробуйте закомментировать строку, указанную в сообщении об ошибке, и, возможно, несколько строк выше.
Если сообщение об ошибке возникает в символе, который сразу же следует за typedef переменной, убедитесь, что переменная определена в исходном коде.
C2059 возникает, когда имя символа препроцессора повторно используется в качестве идентификатора. В следующем примере компилятор видит DIGITS.ONE как число 1, которое недопустимо в качестве имени элемента enum:
Вы можете получить C2059, если символ равен Nothing, как это может произойти, если для компиляции используетсясимвол=/d.
Еще один случай, когда может произойти C2059, — при компиляции приложения, которое указывает структуру в аргументах по умолчанию для функции. Значение аргумента по умолчанию должно быть выражением. Список инициализаторов, например тот, который использовался для инициализации структуры, не является выражением. Чтобы устранить эту проблему, определите конструктор для выполнения необходимой инициализации.
Следующий пример приводит к возникновению ошибки C2059:
C2059 может возникать при неправильном приведении.
Следующий пример приводит к возникновению ошибки C2059:
C2059 также может возникнуть при попытке создать имя пространства имен, содержащее точку.
Следующий пример приводит к возникновению ошибки C2059:
C2059 может возникать, если за оператором, который может квалифицироваться имя ( :: , -> и . ), должно следовать ключевое слово template , как показано в следующем примере:
По умолчанию в C++ предполагается, что AY::Rebind он не является шаблоном, поэтому следующий пример интерпретируется как знак «меньше». Необходимо явно сообщить компилятору, что Rebind является шаблоном, чтобы он мог правильно проанализировать угловую скобку. Чтобы исправить эту ошибку, используйте template ключевое слово в имени зависимого типа, как показано ниже:
Источник
Name already in use
cpp-docs / docs / error-messages / compiler-errors-1 / compiler-error-c2059.md
- Go to file T
- Go to line L
- Copy path
- Copy permalink
Copy raw contents
Copy raw contents
Compiler Error C2059
syntax error : ‘token’
The token caused a syntax error.
The following example generates an error message for the line that declares j .
To determine the cause of the error, examine not only the line that’s listed in the error message, but also the lines above it. If examining the lines yields no clue about the problem, try commenting out the line that’s listed in the error message and perhaps several lines above it.
If the error message occurs on a symbol that immediately follows a typedef variable, make sure that the variable is defined in the source code.
C2059 is raised when a preprocessor symbol name is re-used as an identifier. In the following example, the compiler sees DIGITS.ONE as the number 1, which is not valid as an enum element name:
You may get C2059 if a symbol evaluates to nothing, as can occur when /Dsymbol= is used to compile.
Another case in which C2059 can occur is when you compile an application that specifies a structure in the default arguments for a function. The default value for an argument must be an expression. An initializer list—for example, one that used to initialize a structure—is not an expression. To resolve this problem, define a constructor to perform the required initialization.
The following example generates C2059:
C2059 can occur for an ill-formed cast.
The following sample generates C2059:
C2059 can also occur if you attempt to create a namespace name that contains a period.
The following sample generates C2059:
C2059 can occur when an operator that can qualify a name ( :: , -> , and . ) must be followed by the keyword template , as shown in this example:
By default, C++ assumes that AY::Rebind isn’t a template; therefore, the following is interpreted as a less-than sign. You must tell the compiler explicitly that Rebind is a template so that it can correctly parse the angle bracket. To correct this error, use the template keyword on the dependent type’s name, as shown here:
Источник
Error c2059 syntax error declspec dllexport
Лучший отвечающий
Вопрос
I’m migrating a Win 32 project written in Visual C++ 5.0 to Visual Studio 2012. I get the below error message on building the application.
Error C2059: syntax error : ‘_ declspec(dllexport)’
Clicking on the Error messages it points to the code highlighted in bold.
The above error message repeats for all the code in bold. I could not understand where the error is, could anyone help me to fix this error, it does not look like a syntax error though. Is it a migration error, as the same set of code works fine in vc++ 5.0 without any issues?
I also get the following Errors along with the above mentioned error:
Error C2143: syntax error: missing ‘;’ before ‘<‘
Clicking on the error, it points to the following code. (get_Path is one of the utility functions mentioned in the code snippet above)
/* The following two function sets and gets the path*/
char* EXPORT_FN Get_Path(void) <
Thanks for any help!
Ответы
On 5/7/2013 4:13 AM, suj1234 wrote:
#ifdef __EXPORTING
#define EXPORT_FN __declspec (dllexport) WINAPI
#define C_EXPORT_FN __declspec (dllexport) _cdecl
#else
#define EXPORT_FN __declspec (dllimport) WINAPI
#define C_EXPORT_FN __declspec (dllimport) _cdecl
#endif
char* EXPORT_FN Get_LogFile(void);
The syntax doesn’t allow __declspec where you have it (see http://msdn.microsoft.com/en-us/library/dabb5z75.aspx , second example from the bottom). It should be one of
Only the last version works if you want to keep __declspec and __stdcall (or __cdecl) together. Normally, they are separated into individual macros. For example, this is the declaration in a Windows header:
WINBASEAPI is a macro that expands to __declspec(dllimport) or nothing (and, presumably, to __declspec(dllexport) in the configuration used to actually build Windows from sources), while WINAPI expands to __stdcall. One goes before the return type, the other after.
Источник
Error c2059 syntax error declspec dllexport
This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.
Answered by:
Question
I want to write a native C++ function that I can later access from C#.
Please keep in mind I do not have much experience developing on windows, (mostly unix) and that my only windows compiler is VS2005.
I tried creating a MFC DLL. I am able to access this from a C++ .net program, but not from a C# program using P/Invoke. It seems that a plain MFC DLL is not «good enough» for use with DllImport. Is this correct?
It seems that I have two options:
1) compile the C++ function as a COM DLL (not sure how to do this from VS2005 — I don’t see an option for that). I see an option for an ActiveX DLL. I hope I don’t need to do that.
2) write a C++ .net wrapper class, create a .net assembly, and use that assembly from C#.
I would prefer option 1. how do I create a DLL that C# can use via [DllImport] ?
Answers
You are confusing Platform/Invoke with COM interop. These are two separate interop techniques. As far as which one you should use I would lean toward PInvoke given your newness to Windows programming. PInvoke meets most needs and is simple to use.
For PInvoke all you need is the C signature for a method to call in a DLL. If you want to write your code in C++ then you must: a) create a static or global function in C++ (no class methods), and b) you must mark the function with extern «C» in order to change the namemangling from C++ to C. You can not access C++ classes or class members through PInvoke. Theoretically you can but honestly it is simply too difficult and not worth the effort.
Here is a function you might write in C++:
//In DLL: MyDll.dll
extern «C» double SquareRoot ( double value )
<
//Do work
>
In C# you would do this:
public class MyClass
<
public double SqrRoot ( double value )
<
return SquareRoot(value);
>
[DllImport(«MyDll.dll»)]
private static extern double SquareRoot ( double value );
>
The general rule of thumb is to make these functions private and put a .NET wrapper around it like in the example. DllImport accepts a lot of optional parameter to control character sets, error handling, etc. Furthermore each parameter can be attributed to control marshaling and whatnot but the above example gives you the basics.
If you want to expose an entire class and its methods then you are forced to use COM interop. This requires that you create a COM interface and class using ATL or something and then register the COM object. You then have to import the COM object into a .NET project (or use tlbimp) to generate the COM proxy that .NET will use. You can then use the auto-generated proxy to talk with the COM object. However I’d avoid this if at all possible since it complicates issues and adds to deployment requirements. For more information use MSDN to look up Platform/Invoke and COM Interop.
Michael Taylor — 6/13/06
You are confusing Platform/Invoke with COM interop. These are two separate interop techniques. As far as which one you should use I would lean toward PInvoke given your newness to Windows programming. PInvoke meets most needs and is simple to use.
For PInvoke all you need is the C signature for a method to call in a DLL. If you want to write your code in C++ then you must: a) create a static or global function in C++ (no class methods), and b) you must mark the function with extern «C» in order to change the namemangling from C++ to C. You can not access C++ classes or class members through PInvoke. Theoretically you can but honestly it is simply too difficult and not worth the effort.
Here is a function you might write in C++:
//In DLL: MyDll.dll
extern «C» double SquareRoot ( double value )
<
//Do work
>
In C# you would do this:
public class MyClass
<
public double SqrRoot ( double value )
<
return SquareRoot(value);
>
[DllImport(«MyDll.dll»)]
private static extern double SquareRoot ( double value );
>
The general rule of thumb is to make these functions private and put a .NET wrapper around it like in the example. DllImport accepts a lot of optional parameter to control character sets, error handling, etc. Furthermore each parameter can be attributed to control marshaling and whatnot but the above example gives you the basics.
If you want to expose an entire class and its methods then you are forced to use COM interop. This requires that you create a COM interface and class using ATL or something and then register the COM object. You then have to import the COM object into a .NET project (or use tlbimp) to generate the COM proxy that .NET will use. You can then use the auto-generated proxy to talk with the COM object. However I’d avoid this if at all possible since it complicates issues and adds to deployment requirements. For more information use MSDN to look up Platform/Invoke and COM Interop.
Michael Taylor — 6/13/06
I finally got this to work, but there are some critical steps that have not been mentioned. I will document them in case someone else has the same problem.
First, create the native win32 dll using VS2005:
Create a C++ win32 project. (I called my project «MyWin32Function»). In the wizard, set application type to «DLL». Check the «export symbols» box.
This creates a template file «MyWin32Function.cpp». The template contains an example function, class, and variable to be exported. I deleted the variable and the class. I modified the function to extern «C» and wrote code to simply multiply two floats.
The other important thing in the template (which nobody mentions) is the DllMain at the top. Frankly, I have no idea what that is (I come from a unix background) but it seems to be necessary if you want to link to the dll from another program.
Here is the complete MyWin32Function.cpp:
// MyWin32Function.cpp : Defines the entry point for the DLL application.
//
#include «stdafx.h»
#include «MyWin32Function.h»
#ifdef _MANAGED
#pragma managed(push, off)
#endif
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
<
switch (ul_reason_for_call)
<
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
>
return TRUE;
>
#ifdef _MANAGED
#pragma managed(pop)
#endif
// This is an example of an exported function.
extern «C» MYWIN32FUNCTION_API float fnMyWin32Function(float a,float b)
<
return a*b;
>
I then compiled the file and copied the resulting dll to a directory in my PATH.
The C# side is now fairly easy. I created a C# console project. I did not need to modify any of the default project properties. However, you do need the using Sytem.Runtime.InteropServices! Here is the complete C# file:
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace MyCsharpTest
<
class Program
<
[DllImport(«MyWin32Function.dll»)]
private static extern Single fnMyWin32Function(Single a, Single b);
static void Main(string[] args)
<
Single a = 10.0f;
Single b = 20.0f;
Single c = fnMyWin32Function(a,b);
System.Console.WriteLine(c);
>
>
>
Hopefully this is useful to someone else.
DllMain is not needed in order to export functions. DllMain is a helper routine that DLLs can implement to be notified when they are loaded and unloaded in the process and for each thread. This function is normally used to initialize global variables or run global functions prior to the DLL being used. DllMain is called by Windows after the DLL is loaded but before control returns to the loader (technically the function called is an RTL function that initializes the C++ library and then calls DllMain). The problem with DllMain is the fact that it is loaded within a synchronization block that the loader uses (at least it use to be, not sure whether this is still true in XP) so there are certain things that can’t be done within DllMain.
Most DLLs implement this function simply because each time you create a thread or a thread terminates every DLL loaded in the process has its DllMain called with the appropriate reason code. This is wasteful if the DLL doesn’t care about threads (the general case). Therefore the defacto implementation of this function looks like this:
BOOL WINAPI DllMain ( HMODULE hModule, DWORD dwReason, LPVOID reserved )
<
switch(dwReason)
<
case DLL_PROCESS_ATTACH :
case DLL_PROCESS_DETACH :
case DLL_THREAD_DETACH : break;
case DLL_THREAD_ATTACH :
<
//Disable thread notifications
DisableThreadLibraryCalls(hModule);
>;
>;
>
The other important use of this function is to get the HMODULE for the DLL which you need for some API calls. Note that some frameworks like MFC and ATL use DllMain to perform framework initialization as well.
Источник
description | title | ms.date | f1_keywords | helpviewer_keywords | ms.assetid |
---|---|---|---|---|---|
Learn more about: Compiler Error C2059 |
Compiler Error C2059 |
03/26/2019 |
C2059 |
C2059 |
2be4eb39-3f37-4b32-8e8d-75835e07c78a |
Compiler Error C2059
syntax error : ‘token’
The token caused a syntax error.
The following example generates an error message for the line that declares j
.
// C2059e.cpp // compile with: /c // C2143 expected // Error caused by the incorrect use of '*'. int j*; // C2059
To determine the cause of the error, examine not only the line that’s listed in the error message, but also the lines above it. If examining the lines yields no clue about the problem, try commenting out the line that’s listed in the error message and perhaps several lines above it.
If the error message occurs on a symbol that immediately follows a typedef
variable, make sure that the variable is defined in the source code.
C2059 is raised when a preprocessor symbol name is re-used as an identifier. In the following example, the compiler sees DIGITS.ONE
as the number 1, which is not valid as an enum element name:
#define ONE 1 enum class DIGITS { ZERO, ONE // error C2059 };
You may get C2059 if a symbol evaluates to nothing, as can occur when /Dsymbol= is used to compile.
// C2059a.cpp // compile with: /DTEST= #include <stdio.h> int main() { #ifdef TEST printf_s("nTEST defined %d", TEST); // C2059 #else printf_s("nTEST not defined"); #endif }
Another case in which C2059 can occur is when you compile an application that specifies a structure in the default arguments for a function. The default value for an argument must be an expression. An initializer list—for example, one that used to initialize a structure—is not an expression. To resolve this problem, define a constructor to perform the required initialization.
The following example generates C2059:
// C2059b.cpp // compile with: /c struct ag_type { int a; float b; // Uncomment the following line to resolve. // ag_type(int aa, float bb) : a(aa), b(bb) {} }; void func(ag_type arg = {5, 7.0}); // C2059 void func(ag_type arg = ag_type(5, 7.0)); // OK
C2059 can occur for an ill-formed cast.
The following sample generates C2059:
// C2059c.cpp // compile with: /clr using namespace System; ref class From {}; ref class To : public From {}; int main() { From^ refbase = gcnew To(); To^ refTo = safe_cast<To^>(From^); // C2059 To^ refTo2 = safe_cast<To^>(refbase); // OK }
C2059 can also occur if you attempt to create a namespace name that contains a period.
The following sample generates C2059:
// C2059d.cpp // compile with: /c namespace A.B {} // C2059 // OK namespace A { namespace B {} }
C2059 can occur when an operator that can qualify a name (::
, ->
, and .
) must be followed by the keyword template
, as shown in this example:
template <typename T> struct Allocator { template <typename U> struct Rebind { typedef Allocator<U> Other; }; }; template <typename X, typename AY> struct Container { typedef typename AY::Rebind<X>::Other AX; // error C2059 };
By default, C++ assumes that AY::Rebind
isn’t a template; therefore, the following <
is interpreted as a less-than sign. You must tell the compiler explicitly that Rebind
is a template so that it can correctly parse the angle bracket. To correct this error, use the template
keyword on the dependent type’s name, as shown here:
template <typename T> struct Allocator { template <typename U> struct Rebind { typedef Allocator<U> Other; }; }; template <typename X, typename AY> struct Container { typedef typename AY::template Rebind<X>::Other AX; // correct };
|
|
|
Экспорт функции из dll
, не получается экспортировать фцию, возвращающую указатель.
- Подписаться на тему
- Сообщить другу
- Скачать/распечатать тему
|
|
Full Member Рейтинг (т): 3 |
Мне нужно создать dll и в ней одну функцию экспортировать. не получается.. и не пойму в чем дело.
//h-файл int* __declspec(dllexport) function(); //cpp-файл int* function() { static int var=5; return &var; } На этот код компилятор ругается «error C2059: syntax error : ‘__declspec(dllexport)'» Почему? ЗЫ: на всякий случай — в реале, конечно, используется не эта функция, а посложнее:
extern «C» IUnknown* __declspec(dllexport) CreateInstance() { IUnknown* pI = static_cast<IX*>(new CA) ; pI->AddRef() ; return pI ; } В двух словах — надо в DLL расположить COM-компонент и через эту экспортируемую функцию вернуть указатель на стандарный интерфейс, чтобы в дальнейшем с ним работать.. впрочем сути это не меняет и компилятор выдает ту-же ошибку, ругаясь на возвращаемый указатель. |
trainer |
|
Перенеси __declspec в начало декларации функции. Добавлено 16.05.11, 04:46 |
volod |
|
Full Member Рейтинг (т): 3 |
Большое спасибо! В варианте
//h-файл extern «C» __declspec(dllexport) IUnknown* CreateInstance(void); все заработало.. Можно еще небольшой вопрос, который меня смущает?
extern «C» __declspec(dllexport) IUnknown* CreateInstance(void){/* код фции */}; //так IUnknown* CreateInstance(void){/* код фции */}; //или так.. В общем-то, как я понял, компилятор считает оба определения корректными и принимет за одну функцию.. но какой вариант написания будет более правильным? |
amk |
|
Оба, наверное. Кстати, уверен, что компилятор в этом месте даже предупреждения не выдает? |
volod |
|
Full Member Рейтинг (т): 3 |
Спасибо . Не выдает: warning-ов — ноль. |
amk |
|
Может у тебя эти варнинги просто не включены? |
0 пользователей читают эту тему (0 гостей и 0 скрытых пользователей)
0 пользователей:
- Предыдущая тема
- C/C++: Общие вопросы
- Следующая тема
[ Script execution time: 0,0237 ] [ 16 queries used ] [ Generated: 9.02.23, 12:11 GMT ]
VoltDeMar 18 / 18 / 4 Регистрация: 05.06.2012 Сообщений: 1,020 |
||||
1 |
||||
15.07.2016, 18:50. Показов 1763. Ответов 5 Метки нет (Все метки)
Здравствуйте.
не могу его скомпилировать, ошибка в предпоследней строке, если убрать DLL_OBJECT1 то компилируется, подскажите как исправить.
__________________
0 |
DrOffset 16495 / 8988 / 2205 Регистрация: 30.01.2014 Сообщений: 15,611 |
||||
15.07.2016, 18:59 |
2 |
|||
подскажите как исправить.
1 |
18 / 18 / 4 Регистрация: 05.06.2012 Сообщений: 1,020 |
|
15.07.2016, 22:18 [ТС] |
3 |
Не помогает Миниатюры
0 |
16495 / 8988 / 2205 Регистрация: 30.01.2014 Сообщений: 15,611 |
|
15.07.2016, 22:39 |
4 |
Не помогает Не обманывай
0 |
VoltDeMar 18 / 18 / 4 Регистрация: 05.06.2012 Сообщений: 1,020 |
||||
15.07.2016, 22:54 [ТС] |
5 |
|||
Содержимое файла в котором возникает ошибка выше, за исключением этих заголовков:
Не вру, он вообще пишет missing type, не значит ли это что такой синтаксис неуместен? Добавлено через 2 минуты
это разные имена DLL_OBJECT1 и DLL_OBJECT. Исправил — помогло. Извиняюсь за невнимательность.
0 |
16495 / 8988 / 2205 Регистрация: 30.01.2014 Сообщений: 15,611 |
|
15.07.2016, 22:59 |
6 |
Не вру Я к тому, что твои нынешние ошибки не относятся к первоначальной проблеме вообще никак. Приложи проект, чтобы я оценил степень бедствия. У тебя там может быть что угодно, в том числе 10 слоёв разнообразных ошибок: каждая будет проявляться при исправлении очередной. И каждый раз ты будешь писать, что не помогло. Выложи мне проект(ы), я посмотрю чего ты там наделал Добавлено через 1 минуту
Исправил — помогло Ну вот. А могло быть так, что этого не хватило бы, и вылезло бы еще что-то.
1 |
У меня есть DLL, которую я создал как приложение C ++ Win32. Чтобы предотвратить искажение имени в моей DLL, я использовал определение EXPORT, определенное ниже:
#ifndef EXPORT
#define EXPORT extern "C" __declspec(dllexport)
#endif
EXPORT int _stdcall SteadyFor(double Par[], double Inlet[], double Outlet[]);
Чтобы скомпилировать этот код, мне пришлось зайти в свойства проекта и установить C / C ++ Calling Convention
в __stdcall (/ Gz) и установить Compile As
в Скомпилировать как код C ++ (/ TP).
Это работало в режиме отладки, но режим выпуска бросает error C2059: syntax error: 'string'
на всех моих функциях ЭКСПОРТА — даже если я настроил параметры режима выпуска такими же, как параметры отладки.
Как мне получить режим выпуска для компиляции?
С Уважением,
~ Джо
(Разработка под Visual Studio 2008 Professional)
EDIT:
Много комментариев по поводу моего #define, который, похоже, не вызывает никаких проблем.
Чтобы устранить путаницу, мой заголовочный файл был переписан следующим образом:
#ifndef coilmodel_h
#define coilmodel_h
extern "C" __declspec(dllexport) int _stdcall steadyFor(double Par[], double Inlet[], double Outlet[], char* FileIn, char* FileOut);
#endif
Вот и все.
Ошибка:
Описание error C2059: syntax error: 'string'
Файл coilmodel.h
линия 4
Опять же, эта ошибка появляется только в режиме выпуска, а не в режиме отладки.
Проект представляет собой приложение C ++ Win32 DLL.
У меня есть DLL, которую я создал как приложение С++ Win32. Чтобы предотвратить изменение имени в моей DLL, я использовал определение EXPORT, определенное ниже:
#ifndef EXPORT
#define EXPORT extern "C" __declspec(dllexport)
#endif
EXPORT int _stdcall SteadyFor(double Par[], double Inlet[], double Outlet[]);
Чтобы получить этот код для компиляции, мне пришлось зайти в проект Properties и установить C/С++ Calling Convention
на __ stdcall (/Gz) и установить Compile As
в Скомпилировать как код С++ (/TP).
Это работало в режиме отладки, но режим Release бросает error C2059: syntax error: 'string'
на все мои функции EXPORT, даже если я настроил параметры режима выпуска так же, как и настройки Debug.
Как мне получить режим Release для компиляции?
С уважением,
~ Джо
(Разработка под Visual Studio 2008 Professional)
EDIT:
Много комментариев о моей #define, которая, кажется, не вызывает никаких проблем.
Чтобы устранить путаницу, мой заголовочный файл был переписан следующим образом:
#ifndef coilmodel_h
#define coilmodel_h
extern "C" __declspec(dllexport) int _stdcall steadyFor(double Par[], double Inlet[], double Outlet[], char* FileIn, char* FileOut);
#endif
Вот и все.
Ошибка:
Описание error C2059: syntax error: 'string'
Файл coilmodel.h
Линия 4
Опять же, эта ошибка появляется только в режиме Release, а не в режиме Debug.
Проект — это приложение С++ Win32 DLL.
Я пытаюсь перевести файл заголовка C ++ DLL в заголовок, совместимый с C / C ++. Хотя я получил большинство основных конструкций, я столкнулся с последней проблемой компилятора, которую я не могу объяснить. Следующий код прекрасно работает в C ++, но когда я пытаюсь скомпилировать приложение C, которое просто включает этот файл, я получаю ошибки для определений моей функции в моем заголовочном файле.
Code.h:
typedef void *PVOID;
typedef PVOID HANDLE;
#define WINAPI __stdcall
#ifdef LIB_EXPORTS
#define LIB_API __declspec(dllexport)
#else
#define LIB_API __declspec(dllimport)
#endif
struct ToolState
{
HANDLE DriverHandle;
HANDLE Mutex;
int LockEnabled;
int Type;
};
#ifdef __cplusplus
extern "C" {
#endif
(LIB_API) int SetRate(ToolState *Driver, int rate);
(LIB_API) void EnableLock(ToolState *Driver) ;
(LIB_API) int SendPacket(ToolState *Driver, unsigned char *OutBuffer, int frameSize);
//These also give me the same error:
//LIB_API WINAPI int SendPacket(ToolState *Driver, unsigned char *OutBuffer, int frameSize);
//__declspec(dllimport) WINAPI int SendPacket(ToolState *Driver, unsigned char *OutBuffer, int frameSize);
//Original C++ call that works fine with C++ but has multiple issues in C
//LIB_API int SetRate(ToolState *Driver, int rate);
#ifdef __cplusplus
}
#endif
Ошибки:
error C2059: syntax error : 'type'
error C2059: syntax error : 'type'
error C2059: syntax error : 'type'
Поиск в Google не дал результатов. Следующие темы были близки, но не совсем отвечают на мой вопрос:
Синтаксическая ошибка C2059 при использовании макроса declspec для одной функции; без компиляции нормально
http://support.microsoft.com/kb/117687/en-us
Почему происходит эта синтаксическая ошибка?
1
Решение
В C структуры не являются типами, поэтому вы должны использовать struct Foo
а также enum Bar
где в C ++ вы можете использовать Foo
а также Bar
,
Заметки:
- В C ++ вы все еще можете использовать старый синтаксис, даже если тип является классом.
- В С люди часто используют
typedef struct Foo Foo
который допускает тот же синтаксис, что и в C ++.
3