Error lnk2005 void cdecl

There are many question about this error. But they are related to only a single variable. test.h namespace World { enum Objects { TERRAIN = 1, BOX = 2, SPHERE = 4,...

There are many question about this error. But they are related to only a single variable.

test.h

namespace World
{
    enum Objects
    {
        TERRAIN = 1,
        BOX = 2,
        SPHERE = 4,
        CAPSULE = 8

    };  

    void WorldObjects2(unsigned int mask)
    {
      .......
    }
}

void test();

test.cpp

#include "test.h"

void test()
{
    .......
}

main.cpp

#include "test.h"
int main()
{
    test();
    return 0;
}

When I run these code on visual stduio 2013, it throws an error. It says that error LNK2005: "void __cdecl World::WorldObjects2(unsigned int)" (?WorldObjects2@World@@YAXI@Z) already defined in main.obj. How can I correct this error?

Vlad from Moscow's user avatar

asked May 28, 2015 at 9:03

zakjma's user avatar

1

Your project has two definitions of function WorldObjects2 : one is in the compilation unit test.cpp and other is in the compilation unit main.cpp because the header where the function is defined is included in these two cpp files.

Either use function specifier inline

inline void WorldObjects2(unsigned int mask)
{
    .......
}

Or move the function definition to some cpp file leaving only a function declaration (without its definition) in the header.

Another approach is to make the function as having the internal linkage. For example you could add keyword static

static void WorldObjects2(unsigned int mask)
{
    .......
}

or could place the function in an unnamed namespace within the given namespace.

namespace World
{
    // ...
    namespace
    {
        void WorldObjects2(unsigned int mask)
        {
            .......
        }
    }  
}

Timo's user avatar

Timo

2,1701 gold badge24 silver badges46 bronze badges

answered May 28, 2015 at 9:07

Vlad from Moscow's user avatar

Vlad from MoscowVlad from Moscow

287k23 gold badges179 silver badges323 bronze badges

6

Problem

This technote explains why the error might occur when IBM® Rational® Test RealTime™ instruments a Microsoft® Foundation Class (MFC) application. This application uses dynamic link libraries (DLLs) of the Application Framework Extensions (AFX) .

Symptom

During the instrumentation of an MFC application with AFX DLLs the following error occurs at link time.

The full error message is as follows:

error LNK2005: "void * __cdecl operator new(unsigned int)" already defined

Cause

The Target Deployment Port contains a redefinition of the two C++ functions new and

delete. As a consequence the Target Deplyment Port can now detect memory leaks.

By default the Target Deployment Port on Windows tries to link the application statically. This is not possible with applications that use MFC classes and the AFX DLLs, because it results in a double definition of the new operator.

Resolving The Problem

Modify the settings for the runtime analysis node or the component testing for C++ node. Add the following flags:

Configuration Settings > Build > Compiler > Preprocessor Options: -D_AFXDLL -MD

Configuration Settings > Build > Linker > Link Flags: /nodefaultlib:msvcrt

[{«Product»:{«code»:»SSSHUF»,»label»:»Rational Test RealTime»},»Business Unit»:{«code»:»BU053″,»label»:»Cloud & Data Platform»},»Component»:»—«,»Platform»:[{«code»:»PF033″,»label»:»Windows»}],»Version»:»2003.06.00;2003.06.01;2003.06.12;2003.06.13;2003.06.15;7.0;7.0.0.1;7.0.5″,»Edition»:»»,»Line of Business»:{«code»:»LOB45″,»label»:»Automation»}}]

Historical Number

152827401

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
/* файл table.h */
#define _CRT_SECURE_NO_WARNINGS
 
#ifndef STRUCT_H
#define STRUCT_H
 
#include <stdio.h>
#include <conio.h>
#include <locale.h>
#include <string.h>
#include <stack>
#include <time.h>
#define N 5000
#define k 20
#define m 5
#define Months 13
#define Years 2001
using namespace std;
 
struct elem
{
    char name[k];
    char surname[k];
    int year;
    char month[m];
    int day;
    int number;
};
 
struct table
{
    elem el[N];
    int n;
};
 
#endif 
/* TABLE_H */
 
/* файл funct.cpp */
#include "table.h"
 
int month_in_digit(char *month)
{
    if (strcmp(month, "Jan") == 0)      return 1;
    if (strcmp(month, "Feb") == 0)      return 2;
    if (strcmp(month, "Mar") == 0)      return 3;
    if (strcmp(month, "Apr") == 0)      return 4;
    if (strcmp(month, "May") == 0)      return 5;
    if (strcmp(month, "June") == 0)     return 6;
    if (strcmp(month, "July") == 0)     return 7;
    if (strcmp(month, "Aug") == 0)      return 8;
    if (strcmp(month, "Sept") == 0)     return 9;
    if (strcmp(month, "Oct") == 0)      return 10;
    if (strcmp(month, "Nov") == 0)      return 11;
    if (strcmp(month, "Dec") == 0)      return 12;
}
 
void built_table(table *t, FILE*fp) //построение таблицы
{
    elem x;
    x.name[0] = '';
    x.surname[0] = '';
    x.month[0] = '';
    x.year = 0;
    x.day = 0;
    x.number = 0;
    int i = 0;
    while (t->n< N && fscanf(fp, "%s %s %d %s %d", x.name, x.surname, &x.year, x.month, &x.day) != EOF)
    {
        x.number = month_in_digit(x.month);
        t->el[i].number = x.number;
        strcpy(t->el[i].name, x.name);
        strcpy(t->el[i].surname, x.surname);
        t->el[i].year = x.year;
        strcpy(t->el[i].month, x.month);
        t->el[i].day = x.day;
        t->n++;
        i++;
    }
}
 
void print_table(table *t, FILE *fp, int result_time) //вывод таблицы в файл
{
 
    fprintf(fp, "№tимяttфамилияtгодtмесяцtденьtвремя работыnn");
    for (int i = 0; i < t->n; i++)
        fprintf(fp, "%dt%-10st%-16st%-6dt%-5st%-6dt%-6dtn", i + 1, t->el[i].name, t->el[i].surname, t->el[i].year, t->el[i].month, t->el[i].day, result_time);
}
 
void merge_s(table *t, int first, int end, int key)     //функция сливающая таблицы
{
    int mid, j, start, fin;
    table *s;
    s = new table;
    if (key == 1)
    {
        mid = (first + end) / 2;    //вычисление среднего элемента
        start = first;      //начало левой части
        fin = mid + 1;      //начало правой части
        for (j = first; j <= end; j++)
            if ((start <= mid) && ((fin > end) || (t->el[start].year < t->el[fin].year)))
            {
            s->el[j] = t->el[start];
            s->n++;
            start++;
            }
            else
            {
                s->el[j] = t->el[fin];
                s->n++;
                fin++;
            }
        for (j = first; j <= end; j++)  //возвращение результата в таблицу
            t->el[j] = s->el[j];
    }
    if (key == 2)
    {
        mid = (first + end) / 2;    //вычисление среднего элемента
        start = first;      //начало левой части
        fin = mid + 1;      //начало правой части
        for (j = first; j <= end; j++)
            if ((start <= mid) && ((fin > end) || (t->el[start].number < t->el[fin].number)))
            {
            s->el[j] = t->el[start];
            s->n++;
            start++;
            }
            else
            {
                s->el[j] = t->el[fin];
                s->n++;
                fin++;
            }
        for (j = first; j <= end; j++)  //возвращение результата в таблицу
            t->el[j] = s->el[j];
    }
}
 
void merge_sort(table *t, int first, int end, int key)  //рекурсивная процедура сортировки
{
    if (first < end)
    {
        merge_sort(t, first, (first + end) / 2, key);    //сортировка левой части
        merge_sort(t, (first + end) / 2 + 1, end, key); //сортировка правой части
        merge_s(t, first, end, key);    //слияние двух частей
    }
}
 
void merge(table *t)
{
    int j, l;
    merge_sort(t, 0, t->n, 1);
    for (int i = 0; i<t->n; i++)
    {
        j = i + 1;
        l = j;
        while (t->el[i].year == t->el[j].year && j<t->n - 1)
            j++;
        if (j != l)
        {
            merge_sort(t, i, j - 1, 2);
            i = j - 1;
        }
    }
}
 
void bucket_sort_unique(table *t, int first, int end, int key)
{
    //  stack <elem> *buckets;  //массив стеков
    table *s;
    s = new table;
    if (key == 1)
    {
        //buckets = new stack <elem>[Years];
        for (int i = first; i < end; i++)
        {
            s->el[i] = t->el[i];
            s->n++;
            //buckets[t->el[i].year].push(t->el[i]);    // добавление эл-та
        }
        for (int i = 1, j = first; i < Years; i++)
            while (s->n != 0)
                //while (!buckets[i].empty())       // проверка на пустоту
            {
            t->el[j] = s->el[i];
            //t->el[j] = buckets[i].top;        // ссылка на эл-нт
            //buckets[i].pop;       // удаление эл-та
            j++;
            }
    }
    if (key == 2)
    {
        //buckets = new stack <elem>[Months];
        for (int i = first; i < end; i++)
        {
            s->el[i] = t->el[i];
            s->n++;
            //buckets[t->el[i].number].push(t->el[i]);  // добавление эл-та
        }
        for (int i = 1, j = first; i < Months; i++)
            while (s->n != 0)
                //while (!buckets[i].empty())       // проверка на пустоту
            {
            t->el[j] = s->el[i];
            //t->el[j] = buckets[i].top;        // ссылка на эл-нт
            //buckets[i].pop;       // удаление эл-та
            j++;
            }
    }
}
 
void bucket_sort(table *t)
{
    int j, l;
    bucket_sort_unique(t, 0, t->n, 1);
    for (int i = 0; i<t->n; i++)
    {
        j = i + 1;
        l = j;
        while (t->el[i].year == t->el[j].year && j<t->n - 1)
            j++;
        if (j != l)
        {
            bucket_sort_unique(t, i, j - 1, 2);
            i = j - 1;
        }
    }
}
/* файл main.cpp */
#include "funct.cpp"
 
 
void main() //основная функция
{
//  int y;
    setlocale(LC_ALL, "rus");
    table T;
    FILE *fn;
    FILE *fk;
    fn = fopen("input.txt", "r");
    fk = fopen("output.txt", "w");
    //первая сортировка
    built_table(&T, fn);
    int first_time = clock();
    merge(&T);  //сортировка слиянием
    int end_time = clock();
    int result_time = end_time - first_time;
    fprintf_s(fk, "Сортировка слиянием:n");
    fprintf_s(fk, "nn");
    print_table(&T, fk, result_time);
    //вторая сортировка
    built_table(&T, fn);
    first_time = clock();
    bucket_sort(&T);    //карманная сортировка
    end_time = clock();
    result_time = end_time - first_time;
    fprintf_s(fk, "Карманная сортировка:n");
    fprintf_s(fk, "nn");
    print_table(&T, fk, result_time);
    fclose(fn);
    fclose(fk);
}
  • Remove From My Forums
  • Question

  • Hi All,

    I generated a simple SDI skeleton using the wizard, and tried to #include some of my libraries. It gave me a bunch of ‘LNK2005: … already defined ‘ errors. I repeated the basic SDI generation in another project and this time only tried to include a single, trivial header file:

    mytest.h

    #pragma once
    //#include «stdafx.h»

    void bp5(){
     int a = 0;
     a+=1;
    }

    I include this file in the testDoc.h file of my test project. Despite that this simple header file is so basic, and despite the #pragma once directive, it still gives me the same LNK2005 error!

    Can somebody kick me and tell me what’s wrong???

    Thanks for your sympathy…

    Niko

Answers

  • Let’s detail a bit:

    testDoc.h includes mytest.h

    testDoc.h is included by testDoc.cpp and testView.cpp

    So once the function bp5 will be compiled in testDoc.obj and once in testView.obj. The #pragma once prevents the header file to be included many times in the same .cpp file not in different cpp files.

    You have 2 solutions for this:

    1. make the function inline:

    inline void bp5() {

    int a = 0;

    a += 1;

    }

    2. put the function in a cpp file and in the header add only:

    void bp5();

  • One way to avoid that kind of header hell is to put…

    #ifndef _HEADER_FILE_NAME_H
    #define _HEADER_FILE_NAME_H

    .. at the beginning of the header and …

    #endif // #define _HEADER_FILE_NAME_H

    …at the end.  This will behave the way you expected ‘#pragma once’ to.

  • All the .h files MUST NOT contain any code for functions (except for inline functions).

    You only need to declare the function like in the following line:

    int fn(int b, int c);

    All the function code MUST go in the .cpp files.

    int fn(int b, int c)

    {

    return b + c;

    }

    You MUST NOT #include any .cpp files.

    If you follow this rules then the «already defined in obj file» error should not appear.

The issue is still there in the 1.6.0 version.

Steps to reproduce:
1. downloaded the googletest 1.6.0 version
2. converted the project to VS2008 and built it
3. build my test project with /MTd, linking to gtestd.lib and gtest_maind.lib
4. got errors:

Linking...
msvcprtd.lib(MSVCP90D.dll) : error LNK2005: "public: __thiscall 
std::basic_stringstream<char,struct std::char_traits<char>,class 
std::allocator<char> >::basic_stringstream<char,struct 
std::char_traits<char>,class std::allocator<char> >(int)" 
(??0?$basic_stringstream@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAE@H@Z) 
already defined in gtestd.lib(gtest-all.obj)
msvcprtd.lib(MSVCP90D.dll) : error LNK2005: "public: void __thiscall 
std::basic_stringstream<char,struct std::char_traits<char>,class 
std::allocator<char> >::`vbase destructor'(void)" 
(??_D?$basic_stringstream@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAEXXZ) 
already defined in gtestd.lib(gtest-all.obj)
msvcprtd.lib(MSVCP90D.dll) : error LNK2005: "public: char const * __thiscall 
std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> 
>::c_str(void)const " 
(?c_str@?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QBEPBDXZ) 
already defined in gtestd.lib(gtest-all.obj)
msvcprtd.lib(MSVCP90D.dll) : error LNK2005: "public: __thiscall 
std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> 
>::~basic_string<char,struct std::char_traits<char>,class std::allocator<char> 
>(void)" 
(??1?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAE@XZ) 
already defined in gtestd.lib(gtest-all.obj)
msvcprtd.lib(MSVCP90D.dll) : error LNK2005: "public: class std::locale::facet * 
__thiscall std::locale::facet::_Decref(void)" 
(?_Decref@facet@locale@std@@QAEPAV123@XZ) already defined in 
gtestd.lib(gtest-all.obj)
libcpmtd.lib(ios.obj) : error LNK2005: "private: static void __cdecl 
std::ios_base::_Ios_base_dtor(class std::ios_base *)" 
(?_Ios_base_dtor@ios_base@std@@CAXPAV12@@Z) already defined in 
msvcprtd.lib(MSVCP90D.dll)
libcpmtd.lib(ios.obj) : error LNK2005: "public: static void __cdecl 
std::ios_base::_Addstd(class std::ios_base *)" 
(?_Addstd@ios_base@std@@SAXPAV12@@Z) already defined in 
msvcprtd.lib(MSVCP90D.dll)
libcpmtd.lib(locale0.obj) : error LNK2005: "void __cdecl _AtModuleExit(void 
(__cdecl*)(void))" (?_AtModuleExit@@YAXP6AXXZ@Z) already defined in 
msvcprtd.lib(locale0_implib.obj)
libcpmtd.lib(locale0.obj) : error LNK2005: __Fac_tidy already defined in 
msvcprtd.lib(locale0_implib.obj)
libcpmtd.lib(locale0.obj) : error LNK2005: "private: static void __cdecl 
std::locale::facet::facet_Register(class std::locale::facet *)" 
(?facet_Register@facet@locale@std@@CAXPAV123@@Z) already defined in 
msvcprtd.lib(locale0_implib.obj)
libcpmtd.lib(locale0.obj) : error LNK2005: "private: static class 
std::locale::_Locimp * __cdecl std::locale::_Getgloballocale(void)" 
(?_Getgloballocale@locale@std@@CAPAV_Locimp@12@XZ) already defined in 
msvcprtd.lib(MSVCP90D.dll)
libcpmtd.lib(locale0.obj) : error LNK2005: "private: static class 
std::locale::_Locimp * __cdecl std::locale::_Init(void)" 
(?_Init@locale@std@@CAPAV_Locimp@12@XZ) already defined in 
msvcprtd.lib(MSVCP90D.dll)
libcpmtd.lib(locale0.obj) : error LNK2005: "public: static void __cdecl 
std::_Locinfo::_Locinfo_ctor(class std::_Locinfo *,class 
std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> 
> const &)" 
(?_Locinfo_ctor@_Locinfo@std@@SAXPAV12@ABV?$basic_string@DU?$char_traits@D@std@@
V?$allocator@D@2@@2@@Z) already defined in msvcprtd.lib(MSVCP90D.dll)
libcpmtd.lib(locale0.obj) : error LNK2005: "public: static void __cdecl 
std::_Locinfo::_Locinfo_dtor(class std::_Locinfo *)" 
(?_Locinfo_dtor@_Locinfo@std@@SAXPAV12@@Z) already defined in 
msvcprtd.lib(MSVCP90D.dll)
libcpmtd.lib(xlock.obj) : error LNK2005: "public: __thiscall 
std::_Lockit::_Lockit(int)" (??0_Lockit@std@@QAE@H@Z) already defined in 
msvcprtd.lib(MSVCP90D.dll)
libcpmtd.lib(xlock.obj) : error LNK2005: "public: __thiscall 
std::_Lockit::~_Lockit(void)" (??1_Lockit@std@@QAE@XZ) already defined in 
msvcprtd.lib(MSVCP90D.dll)
LIBCMTD.lib(_file.obj) : error LNK2005: ___iob_func already defined in 
MSVCRTD.lib(MSVCR90D.dll)
LIBCMTD.lib(osfinfo.obj) : error LNK2005: __open_osfhandle already defined in 
MSVCRTD.lib(MSVCR90D.dll)
LIBCMTD.lib(dosmap.obj) : error LNK2005: __errno already defined in 
MSVCRTD.lib(MSVCR90D.dll)
LIBCMTD.lib(tidtable.obj) : error LNK2005: __encode_pointer already defined in 
MSVCRTD.lib(MSVCR90D.dll)
LIBCMTD.lib(tidtable.obj) : error LNK2005: __decode_pointer already defined in 
MSVCRTD.lib(MSVCR90D.dll)
LIBCMTD.lib(fflush.obj) : error LNK2005: _fflush already defined in 
MSVCRTD.lib(MSVCR90D.dll)
LIBCMTD.lib(lconv.obj) : error LNK2005: _localeconv already defined in 
MSVCRTD.lib(MSVCR90D.dll)
LIBCMTD.lib(crt0dat.obj) : error LNK2005: _exit already defined in 
MSVCRTD.lib(MSVCR90D.dll)
LIBCMTD.lib(crt0dat.obj) : error LNK2005: __exit already defined in 
MSVCRTD.lib(MSVCR90D.dll)
LIBCMTD.lib(invarg.obj) : error LNK2005: __invalid_parameter already defined in 
MSVCRTD.lib(MSVCR90D.dll)
LIBCMTD.lib(mlock.obj) : error LNK2005: __lock already defined in 
MSVCRTD.lib(MSVCR90D.dll)
LIBCMTD.lib(mlock.obj) : error LNK2005: __unlock already defined in 
MSVCRTD.lib(MSVCR90D.dll)
LIBCMTD.lib(dbghook.obj) : error LNK2005: __crt_debugger_hook already defined 
in MSVCRTD.lib(MSVCR90D.dll)
LIBCMTD.lib(stricmp.obj) : error LNK2005: __stricmp already defined in 
MSVCRTD.lib(MSVCR90D.dll)
LIBCMTD.lib(hooks.obj) : error LNK2005: "void __cdecl terminate(void)" 
(?terminate@@YAXXZ) already defined in MSVCRTD.lib(MSVCR90D.dll)
LIBCMTD.lib(sprintf.obj) : error LNK2005: _sprintf_s already defined in 
MSVCRTD.lib(MSVCR90D.dll)
LIBCMTD.lib(getenv.obj) : error LNK2005: _getenv already defined in 
MSVCRTD.lib(MSVCR90D.dll)
LIBCMTD.lib(strtol.obj) : error LNK2005: _strtol already defined in 
MSVCRTD.lib(MSVCR90D.dll)
LIBCMTD.lib(strtoq.obj) : error LNK2005: __strtoui64 already defined in 
MSVCRTD.lib(MSVCR90D.dll)
LIBCMTD.lib(dbgrptw.obj) : error LNK2005: __CrtDbgReportW already defined in 
MSVCRTD.lib(MSVCR90D.dll)
LIBCMTD.lib(vsnprnc.obj) : error LNK2005: __vsnprintf_s already defined in 
MSVCRTD.lib(MSVCR90D.dll)
LIBCMTD.lib(printf.obj) : error LNK2005: _printf already defined in 
MSVCRTD.lib(MSVCR90D.dll)
LIBCMTD.lib(vprintf.obj) : error LNK2005: _vprintf already defined in 
MSVCRTD.lib(MSVCR90D.dll)
LINK : warning LNK4098: defaultlib 'MSVCRTD' conflicts with use of other libs; 
use /NODEFAULTLIB:library
C:XXXX : fatal error LNK1169: one or more multiply defined symbols found

Error executing link.exe (tool returned code: 1169)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
#pragma once
#include "afxdlgs.h"
#include <stdio.h>
#include <stdlib.h>
#include "SimAnneal.h"


namespace SeparateChart2
{
	using namespace System;
	using namespace System::ComponentModel;
	using namespace System::Collections;
	using namespace System::Windows::Forms;
	using namespace System::Data;
	using namespace System::Drawing;

	double dataArray [10000];
	/// <summary> 
	/// Summary for Form1
	///
	/// WARNING: If you change the name of this class, you will need to change the 
	///          'Resource File Name' property for the managed resource compiler tool 
	///          associated with all .resx files this class depends on.  Otherwise,
	///          the designers will not be able to interact properly with localized
	///          resources associated with this form.
	/// </summary>
	public __gc class Form1 : public System::Windows::Forms::Form
	{	
	public:
		int data_length;
		Form1(void)
		{
			InitializeComponent();
		}
  
	protected:
		void Dispose(Boolean disposing)
		{
			if (disposing && components)
			{
				components->Dispose();
			}
			__super::Dispose(disposing);
		}
	private: System::Windows::Forms::Button *  button1;
	private: System::Windows::Forms::TextBox *  textBox1;
	private: System::Windows::Forms::Button *  button2;

	private:
		/// <summary>
		/// Required designer variable.
		/// </summary>
		System::ComponentModel::Container * components;

		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		void InitializeComponent(void)
		{
			this->button1 = new System::Windows::Forms::Button();
			this->textBox1 = new System::Windows::Forms::TextBox();
			this->button2 = new System::Windows::Forms::Button();
			this->SuspendLayout();
			// 
			// button1
			// 
			this->button1->Location = System::Drawing::Point(16, 72);
			this->button1->Name = S"button1";
			this->button1->Size = System::Drawing::Size(152, 40);
			this->button1->TabIndex = 0;
			this->button1->Text = S"Load data...";
			this->button1->Click += new System::EventHandler(this, button1_Click);
			// 
			// textBox1
			// 
			this->textBox1->Location = System::Drawing::Point(16, 32);
			this->textBox1->Name = S"textBox1";
			this->textBox1->Size = System::Drawing::Size(168, 22);
			this->textBox1->TabIndex = 1;
			this->textBox1->Text = S"D:\myinfomation\simulated annealing\h1.txt";
			// 
			// button2
			// 
			this->button2->Location = System::Drawing::Point(16, 128);
			this->button2->Name = S"button2";
			this->button2->Size = System::Drawing::Size(144, 40);
			this->button2->TabIndex = 2;
			this->button2->Text = S"Save results";
			this->button2->Click += new System::EventHandler(this, button2_Click);
			// 
			// Form1
			// 
			this->AutoScaleBaseSize = System::Drawing::Size(6, 15);
			this->ClientSize = System::Drawing::Size(292, 268);
			this->Controls->Add(this->button2);
			this->Controls->Add(this->textBox1);
			this->Controls->Add(this->button1);
			this->Name = S"Form1";
			this->Text = S"Form1";
			this->ResumeLayout(false);

		}	
	private: System::Void button1_Click(System::Object *  sender, System::EventArgs *  e)
			 {
				 	/*CFileDialog fdlg (TRUE);
					if(fdlg.DoModal()!=IDOK)
						return;
					CString fname = fdlg.GetPathName();*/
				 FILE *fid = fopen(/*fname*/ /*textBox1 -> Text ->ToCharArray ()*/"D:\myinfomation\simulated annealing\h1.txt", "r");
					int i = 0;
					while((!feof(fid)) && (i<10000)) {
						fscanf(fid, "%f", &dataArray [i]);
						i++;
					}
					data_length = i;
					fclose(fid);
//	return TRUE;
			 }

	private: System::Void button2_Click(System::Object *  sender, System::EventArgs *  e)
			 {
				 int sa_res [1000];
				 int res_length = SeparateChart (dataArray, sa_res, data_length, 50, 6);
				 FILE *fid = fopen("C:\temp\sa_res.txt", "w");
				 for (int i = 0; i < res_length; i++)
					 fprintf (fid, "%frn", &sa_res [i]);
				 fclose (fid);
			 }

	};
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#include "StdAfx.h"
#include <cmath>
#include ".simanneal.h"

int ApplySimAnneal(double *chart, int chart_length, int dir, int start, int scatter, int minx)
{
	double Tinit = 1;
	double minT = 1e-8;
	int max_consec_rejections = 1000;
	int max_try = 300;
	int max_success = 20;
	double k = 1;
	double Tgrad = 0.8;

	int itry = 0;
	int parent = start;
	int success = 0;
	bool finished = false;
	int consec = 0;
	double T = Tinit;
	double initenergy = chart [parent];
	double newenergy, oldenergy;
	int total = 0;
	int current, newparam=0;
	oldenergy = chart [0];
	while (!finished) {
		itry++;
		current=parent;
		if ((itry >= max_try) || (success >= max_success) || (T < minT) || (consec >= max_consec_rejections)) {
			finished = true;
			total = total + itry;
			break;
		}
		else {
			T = Tgrad*T;
			total = total + itry;
			itry=1;
			success = 1;
		}
		newparam = current + scatter*rand ();
		if (newparam < minx)
			newparam = minx;
		if (newparam >= chart_length)
			newparam = chart_length;
		newenergy = chart [newparam];
		if ((oldenergy - newenergy)*dir > 1e-6*dir) {
			parent = newparam;
			oldenergy = newenergy;
			success++;
			consec = 0;
		}
		else {
			if (rand ()*dir < dir*exp ((oldenergy - newenergy) / (k*T))){
				parent = newparam;
				oldenergy = newenergy;
				success++;
			}
			else
				consec++;
		}
	}
	return parent;
}

int HighestCoincidence(int *values, int count)
{
	int coinccount [10];
	int coincvalues [10];
	int coinctotal = 0;
	int i;
	for (i = 0; i < count; i++){
		bool coincfound = false;
		for (int j = 0; j < coinctotal; j++)
			if (values [i] == coincvalues [j]){
				coinccount [j]++;
				coincfound = true;
			}
			if (!coincfound) {
				coincvalues [coinctotal] = values [i];
				coinctotal ++;
			}
	}
	int maxcoinc = 0;
	for (i = 1; i < coinctotal; i++)
		if (coinccount [i] > coinccount [maxcoinc])
			i = maxcoinc;
	return coincvalues [maxcoinc];
}

int RepeatSA(double * chart, int chart_length, int dir, int start, int scatter, int minx)
{
	int sa_results [9];
	for (int i = 0; i < 9; i++)
		sa_results [i] = ApplySimAnneal (chart, chart_length, dir, start, scatter, minx);
	return HighestCoincidence (sa_results, 9);
}

int SeparateChart(double * chart, int * result, int chart_length, int nvs, int scatter)
{
	int dir, current = 0;
	int total = 0;
	if (RepeatSA (chart, chart_length, 1, nvs, scatter, 0) > RepeatSA (chart, chart_length, -1, nvs, scatter, 0))
		dir = -1;
	else
		dir = 1;
	while (current + nvs < chart_length){
		current = RepeatSA(chart, chart_length, dir, current + nvs, scatter, current);
		dir = -dir;
		result [total] = current;
		total++;
	}	
	return total;
}

As I could guess about possbile redefinings may be it can be #include «StdAfx.h» and #include «afxdlgs.h». But both modules don’t work without it. So how to define it to make the project linkable.

still remain 2 errors

fconv.obj : error LNK2005: «void * __cdecl process(void *)» (?process@@YAPEAXPEAX@Z) already defined in fconvblas.obj

fconv.obj : error LNK2005: mexFunction already defined in fconvblas.obj

with the help of this thread

remaining 3 errors errors are removed

fconvblas.obj : error LNK2019: unresolved external symbol __imp_pthread_exit referenced in function «void * __cdecl process(void *)» (?process@@YAPEAXPEAX@Z)

fconvblas.obj : error LNK2019: unresolved external symbol __imp_pthread_join referenced in function mexFunction

fconvblas.obj : error LNK2019: unresolved external symbol __imp_pthread_create referenced in function mexFunction

fconvblas.mexw64 : fatal error LNK1120: 3 unresolved externals

http://www.mathworks.com/matlabcentral/answers/107106-error-lnk2019-unresolved-external-symbol-when-compiling-mex

I gave path of library folder, lib file name, header folder location

mex -O -I»C:UsershassanDesktopPthreadinclude» -lpthreadVC2 -L»C:UsershassanDesktopPthreadlibx64″ fconvblas.cc -lmwblas -O fconv.c

Any idea to remove other 2 remaaing errors? what is meant by mexFunction already defined in fconvblas.obj

Понравилась статья? Поделить с друзьями:
  • Error lnk2005 fortran
  • Error lnk2005 already defined in libcmtd lib
  • Error lnk2001 неразрешенный внешний символ main
  • Error lnk2001 неразрешенный внешний символ cxxframehandler3
  • Error lnk2001 unresolved external symbol winmain 16