Kojans 2 / 2 / 4 Регистрация: 27.01.2015 Сообщений: 48 |
||||||||
1 |
||||||||
31.01.2015, 19:05. Показов 15317. Ответов 16 Метки нет (Все метки)
Взял код для графического интерфейса от сюда:
а он ошибки:
0 |
120 / 142 / 46 Регистрация: 31.10.2014 Сообщений: 721 Записей в блоге: 1 |
|
01.02.2015, 10:13 |
2 |
потому что код не С и не С++, а какая то сборная солянка.
0 |
2 / 2 / 4 Регистрация: 27.01.2015 Сообщений: 48 |
|
01.02.2015, 11:46 [ТС] |
3 |
Напиши тогда, как правильно.
0 |
demmax2004 120 / 142 / 46 Регистрация: 31.10.2014 Сообщений: 721 Записей в блоге: 1 |
||||
01.02.2015, 12:17 |
4 |
|||
0 |
2 / 2 / 4 Регистрация: 27.01.2015 Сообщений: 48 |
|
01.02.2015, 13:33 [ТС] |
5 |
error C2601: ‘SendToCalc’ : local function definitions are illegal
0 |
120 / 142 / 46 Регистрация: 31.10.2014 Сообщений: 721 Записей в блоге: 1 |
|
01.02.2015, 14:19 |
6 |
Добавь ее в класс если нужно
0 |
Модератор 8809 / 6592 / 894 Регистрация: 14.02.2011 Сообщений: 23,178 |
|
01.02.2015, 14:40 |
7 |
main.cpp
error LNK2028: unresolved token (0A000037) «extern «C» int __stdcall PostMessageW есть подозрение, что код для винды, а проект сделан под консоль
0 |
Kojans 2 / 2 / 4 Регистрация: 27.01.2015 Сообщений: 48 |
||||
01.02.2015, 15:26 [ТС] |
8 |
|||
да, я хотел консольное переделать в вин Добавлено через 14 минут
Добавь ее в класс если нужно
0 |
120 / 142 / 46 Регистрация: 31.10.2014 Сообщений: 721 Записей в блоге: 1 |
|
01.02.2015, 16:24 |
9 |
есть подозрение, что код для винды, а проект сделан под консоль Без разницы.
referenced in function «private: void __clrcall WinForm::MyForm::SendToCalc(void)» Зачем ты опять пользуешься НЕ языком программирования С++ ?????
0 |
Kojans 2 / 2 / 4 Регистрация: 27.01.2015 Сообщений: 48 |
||||
01.02.2015, 16:28 [ТС] |
10 |
|||
Подставь сюда, чтобы работало
0 |
Модератор 8809 / 6592 / 894 Регистрация: 14.02.2011 Сообщений: 23,178 |
|
01.02.2015, 16:38 |
11 |
я хотел консольное переделать в вин да судя по этому тебе лучше уйти в специализированную ветку
Без разницы. Серьезно?
ты опять пользуешься НЕ языком программирования С++ это язык c++ cli(у Visual Studio это CLR)
0 |
120 / 142 / 46 Регистрация: 31.10.2014 Сообщений: 721 Записей в блоге: 1 |
|||||
01.02.2015, 17:12 |
12 |
||||
Подставь сюда, чтобы работало Это не С++. Пиши код на С++ Добавлено через 55 секунд
и консолька не поддерживает виндовые библиотеки?без лишних телодвижений У меня все без проблем делается, видимо у меня руки прямые и из нужных мест растут.
0 |
Администратор 9392 / 4676 / 757 Регистрация: 17.04.2012 Сообщений: 9,519 Записей в блоге: 14 |
|
07.02.2015, 13:15 |
13 |
Сообщение было отмечено Kojans как решение РешениеKojans, нужно добавить зависимости в свойствах проекта: открываете свойства проекта, там идёте по «Компоновщик — Ввод — Дополнительные зависимости» Добавляете библиотеки advapi32.lib, kernel32.lib и user32.lib Теперь должно нормально скомпоноваться.
8 |
Kojans 2 / 2 / 4 Регистрация: 27.01.2015 Сообщений: 48 |
||||
07.02.2015, 19:42 [ТС] |
14 |
|||
Компилируется без ошибок, но ничего не выполняется.
Подскажете, как это переделать под c++ cli?
0 |
Администратор 9392 / 4676 / 757 Регистрация: 17.04.2012 Сообщений: 9,519 Записей в блоге: 14 |
|
07.02.2015, 20:14 |
15 |
но ничего не выполняется Калькулятор открыт? Если вы на Windows 7, то окно просто «Калькулятор».
0 |
Модератор 8809 / 6592 / 894 Регистрация: 14.02.2011 Сообщений: 23,178 |
|
07.02.2015, 20:14 |
16 |
Hop = FindWindow проверять нужно нашел /не нашел
0 |
2 / 2 / 4 Регистрация: 27.01.2015 Сообщений: 48 |
|
07.02.2015, 20:38 [ТС] |
17 |
Но GetPixel работает.
0 |
IT_Exp Эксперт 87844 / 49110 / 22898 Регистрация: 17.06.2006 Сообщений: 92,604 |
07.02.2015, 20:38 |
Помогаю со студенческими работами здесь Error LNK2028, LNK2019, LNK1120: 2 неразрешенных внешних элементов Ошибки LNK2019 и LNK2001 при сборке проекта Ошибки на этапе линковки, при работе с шаблонами (LNK2019) Error LNK1120, error LNK2019, error LNK2028, queue // строка, из-за… Искать еще темы с ответами Или воспользуйтесь поиском по форуму: 17 |
I have got a .dll file and .lib file. For these I have also header files.
When I am writing a console application with these files, everything is Ok. Our program ran. But, when I try to write windows application with VStudio .NET2005 C++, I got these errors.
________________
Error 1 error LNK2028: unresolved token (0A000010) «public: static class My1614::ATDeviceManager * __cdecl My1614::ATDeviceManager::Instance(void)» (?Instance@ATDeviceManager@My1614@@$$FSAPAV12@XZ) referenced in function «private: void __clrcall My1614::Form1::button1_Click(class System:bject ^,class System::EventArgs ^)» (?button1_Click@Form1@My1614@@$$FA$AAMXP$AAVObject@System@@P$AAVEventArgs@4@@Z) 1614.obj
Error 2 error LNK2019: unresolved external symbol «public: static class My1614::ATDeviceManager * __cdecl My1614::ATDeviceManager::Instance(void)» (?Instance@ATDeviceManager@My1614@@$$FSAPAV12@XZ) referenced in function «private: void __clrcall My1614::Form1::button1_Click(class System:bject ^,class System::EventArgs ^)» (?button1_Click@Form1@My1614@@$$FA$AAMXP$AAVObject@System@@P$AAVEventArgs@4@@Z) 1614.obj
Error 3 fatal error LNK1120: 2 unresolved externals C:UsersmeeDocumentsVisual Studio 2005Projects1614Debug1614.exe
_________________
* I also write the library information in «Project->Properties->Linker->Additional Dependicies—> «
* I think the problem is relevant with manage code or unmanaged code. But if it is even yes, I did not solve the problem.
What is wrong?
Permalink
Cannot retrieve contributors at this time
description | title | ms.date | f1_keywords | helpviewer_keywords | ms.assetid |
---|---|---|---|---|---|
Learn more about: Linker Tools Error LNK2028 |
Linker Tools Error LNK2028 |
11/04/2016 |
LNK2028 |
LNK2028 |
e2b03293-6066-464d-a050-ce747bcf7f0e |
«exported_function» (decorated_name) referenced in function «function_containing_function_call» (decorated_name)
Remarks
When attempting to import a native function into a pure image, remember that the implicit calling conventions differ between native and pure compilations.
The /clr:pure compiler option is deprecated in Visual Studio 2015 and unsupported in Visual Studio 2017.
Examples
This code sample generates a component with an exported, native, function whose calling convention is implicitly __cdecl.
// LNK2028.cpp // compile with: /LD __declspec(dllexport) int func() { return 3; }
The following sample creates a pure client that consumes the native function. However, the calling convention under /clr:pure is __clrcall. The following sample generates LNK2028.
// LNK2028_b.cpp // compile with: /clr:pure lnk2028.lib // LNK2028 expected int func(); int main() { return func(); }
The following code is taken from here. I removed all Windows NT part as I am working on Windows 7.
I copied this code and run in visual studio 2010 (New project-> VC++->CLR->CLR Console… ). But it is giving lots of unresolved extern ‘c’ errors as listed below the code. What wrong I have committed?
#define STRICT 1
#include <windows.h>
#include <iostream>
using namespace std;
BOOL CALLBACK EnumWindowsProc(HWND hWnd, LPARAM lParam) {
DWORD dwThreadId, dwProcessId;
HINSTANCE hInstance;
char String[255];
HANDLE hProcess;
if (!hWnd)
return TRUE; // Not a window
if (!::IsWindowVisible(hWnd))
return TRUE; // Not visible
if (!SendMessage(hWnd, WM_GETTEXT, sizeof(String), (LPARAM)String))
return TRUE; // No window title
hInstance = (HINSTANCE)GetWindowLong(hWnd, GWL_HINSTANCE);
dwThreadId = GetWindowThreadProcessId(hWnd, &dwProcessId);
hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwProcessId);
cout << hWnd << ' ' << dwProcessId << 't' << String << 't';
cout << "(None)n";
CloseHandle(hProcess);
return TRUE;
}
int main(int argc, char *argv[], char *envp[]) {
EnumWindows(EnumWindowsProc, NULL);
return 0;
}
This is giving following Errors(and other similar unresolved extern C errors)
1>wndowfind.obj : error LNK2028: unresolved token (0A000342) "extern "C" int __stdcall
EnumWindows(int (__stdcall*)(struct HWND__ *,long),long)" 3
(?EnumWindows@@$$J18YGHP6GHPAUHWND__@@J@ZJ@Z) referenced in function "int __cdecl
main(int,char * * const,char * * const)" (?main@@$$HYAHHQAPAD0@Z)
1>wndowfind.obj : error LNK2028: unresolved token (0A000346) "extern "C" unsigned long
__stdcall GetWindowThreadProcessId(struct HWND__ *,unsigned long *)"
(?GetWindowThreadProcessId@@$$J18YGKPAUHWND__@@PAK@Z) referenced in function "int __stdcall
EnumWindowsProc(struct HWND__ *,long)" (?EnumWindowsProc@@$$FYGHPAUHWND__@@J@Z)
1>wndowfind.obj : error LNK2028: unresolved token (0A000347) "extern "C" long __stdcall
GetWindowLongW(struct HWND__ *,int)" (?GetWindowLongW@@$$J18YGJPAUHWND__@@H@Z) referenced in
function "int __stdcall EnumWindowsProc(struct HWND__ *,long)"
(?EnumWindowsProc@@$$FYGHPAUHWND__@@J@Z)
1>wndowfind.obj : error LNK2019: unresolved external symbol "extern "C" int __stdcall
EnumWindows(int (__stdcall*)(struct HWND__ *,long),long)"
(?EnumWindows@@$$J18YGHP6GHPAUHWND__@@J@ZJ@Z) referenced in function "int __cdecl
main(int,char * * const,char * * const)" (?main@@$$HYAHHQAPAD0@Z)
1>c:usersafnandocumentsvisual studio 2010ProjectswndowfindDebugwndowfind.exe : fatal
error LNK1120: 10 unresolved externals
1>
1>Build FAILED.
UPDATED
By including the libraries (as suggested in the answers), I was able to run the program successfully. But I am not able to understand why only first character of string is printing not the complete one, as can be seen in the output:
00010060 2652 S (None)
002502B2 5820 C (None)
00090402 5160 w (None)
00050392 5160 w (None)
00060292 3520 F (None)
000C02BA 3520 M (None)
0001021A 3736 E (None)
00040018 896 I (None)
00010170 3580 A (None)
0002003E 2684 D (None)
00030316 4956 N (None)
000202DE 3736 D (None)
0001031E 2652 S (None)
000100EA 2652 P (None)
In the output above, S is actually «start», C is «console» etc I confirmed through spy++ tool.
How can I print the complete string instead of just first character?
У меня есть проект C, из которого я экспортирую функцию f()
и вызвать его из другого проекта C ++, и он отлично работает. Тем не менее, когда я вызываю какую-то другую функцию g()
внутри f
Я получаю LNK2028 ошибку.
Минимальный пример C
Проект выглядит так:
test.h
#ifndef TEST_H
#define TEST_H
#include "myfunc.h"#define EXTERN_DLL_EXPORT extern "C" __declspec(dllexport)
EXTERN_DLL_EXPORT void f()
{
g(); // this will provide LNK2028 if f() is called from other project
}
#endif
myfunc.h
void g();
myfunc.c
#include "myfunc.h"void g(){}
Сам проект строится. Однако, когда я вызываю эту функцию из других C++/CLI
проект
#include "Test.h"public ref class CppWrapper
{
public:
CppWrapper(){ f(); } // call external function
};
Я получаю ошибку:
error LNK2028: unresolved token (0A00007C) "void __cdecl g(void)" (?g@@$$FYAXXZ) referenced in function "extern "C" void __cdecl f(void)" (?f@@$$J0YAXXZ) main.obj CppWrapper
error LNK2019: unresolved external symbol "void __cdecl g(void)" (?g@@$$FYAXXZ) referenced in function "extern "C" void __cdecl f(void)" (?f@@$$J0YAXXZ) main.obj CppWrapper
Дополнительные детали:
- Я установил платформу x64 для всего решения
- В CppWrapper включаю
.lib
файл из проекта C
1
Решение
test.h
#ifndef TEST_H
#define TEST_H
#ifdef BUILDING_MY_DLL
#define DLL_EXPORT __declspec(dllexport)
#else
#define DLL_EXPORT __declspec(dllimport)
#endif
#ifdef __cplusplus
extern "C" {
#endif
DLL_EXPORT void f();
#ifdef __cplusplus
}
#endif
#endif
test.c
#include "Test.h"#include "myfunc.h"
void f()
{
g();
}
В ваш проект C вы должны добавить BUILDING_MY_DLL
в
Configuration Properties > C/C++ > Preprocessor > Preprocessor Definitions
Единственное реальное изменение заключается в том, что я добавил переключатель между __declspec(dllexport)
а также __declspec(dllimport)
, Требуются изменения:
- Перевезу
f
тело кTest.c
потому что функции импортированы с__declspec(dllimport)
не может иметь определение уже.
Другие изменения:
- Никогда не пиши
extern "C"
без#ifdef __cplusplus
guard, или многие компиляторы C не будут компилировать ваш код.
2
Другие решения
Я просто провел 2 дня, борясь с этой же проблемой. Спасибо за решение. Я хотел бы расширить это.
В моем случае я вызываю функцию c из экспортированной dll-функции c ++ и получаю ту же ошибку. Мне удалось исправить это так (на вашем примере)
#ifndef TEST_H
#define TEST_H
#ifdef BUILDING_MY_DLL
#define DLL_EXPORT __declspec(dllexport)
#else
#define DLL_EXPORT __declspec(dllimport)
#endif
#ifdef __cplusplus
extern "C" {
#endif
#include "myfunc.h"
#ifdef __cplusplus
}
#endif
#endif
0