Ошибка VS 2012 LNK2001: неразрешенный внешний символ

Сейчас я изучаю тестирование производительности верторизации, но встречаю следующие ошибки

1> ConsoleApplication2.obj: ошибка LNK2001: неразрешенный внешний символ «частный: статическое объединение _LARGE_INTEGER Timer :: m_freq» (? M_freq @ Timer @@ 0T_LARGE_INTEGER @@ A) 1> ConsoleApplication2.obj: ошибка LNK2001: неразрешенный внешний символ «частный» static __int64 Timer :: m_overhead "(? m_overhead @ Timer @@ 0_JA) 1> c: \ users \ lara feodorovna \ documents \ visual studio 2012 \ Projects \ ConsoleApplication2 \ Debug \ ConsoleApplication2.exe: фатальная ошибка LNK1120: 2 неразрешенных внешних элемента

--------------- timer.h (я вручную добавил) ---------------

#pragma once
#include <windows.h>

struct Timer
{
     void Start() 
     {
         QueryPerformanceCounter(&m_start);
     }

     void Stop() 
     {
         QueryPerformanceCounter(&m_stop);
     }

     // Returns elapsed time in milliseconds (ms)
     double Elapsed()
     {
         return (m_stop.QuadPart - m_start.QuadPart - m_overhead) \
                                           * 1000.0 / m_freq.QuadPart;
     }

 private:

     // Returns the overhead of the timer in ticks
     static LONGLONG GetOverhead()
     {
         Timer t;
         t.Start();
         t.Stop();
         return t.m_stop.QuadPart - t.m_start.QuadPart;
     }

     LARGE_INTEGER m_start;
     LARGE_INTEGER m_stop;
     static LARGE_INTEGER m_freq;
     static LONGLONG m_overhead;
};

--------------------- ConsolApplication2.cpp -----------------------

#include "stdafx.h"
#include "timer.h"

const int MAXNUM = 100000;

int a[MAXNUM];
int b[MAXNUM];
int c[MAXNUM];

int _tmain(int argc, _TCHAR* argv[])
{
    Timer timer;
    double time_NoVector;
    double time_Vector;

    //No Vectorization
    timer.Start();
    #pragma loop(no_vector)
    for (int j=0; j<MAXNUM; j++)
    {
        c[j]=a[j]+b[j];
    }
    timer.Stop();
    time_NoVector=timer.Elapsed();

    //Vectorization
    timer.Start();
    for(int j=0; j <MAXNUM; j++)
    {
        c[j] = a[j] + b[j];
    }
    timer.Stop();
    time_Vector=timer.Elapsed();

    printf("---------------------------------------------\n");
    printf("%-14s %10s %10s\n", "Version", "Times(s)", "Speedup");
    printf("---------------------------------------------\n");
    printf("%-14s %10.4f %10.4f\n", "NoVector", time_NoVector, 1.0);
    printf("%-14s %10.4f %10.4f\n\n", "Vector", time_Vector, time_NoVector / time_Vector);

    return 0;

}

пожалуйста, помогите мне


person user1349407    schedule 07.09.2013    source источник


Ответы (3)


Когда у вас есть static участников в class, вы должны определить его в единице перевода.

В шапке:

struct Timer
{
    // ...

    // Declaration of your static members
    static LARGE_INTEGER m_freq;
    static LONGLONG m_overhead;
};

В .cpp:

// Definitions
LARGE_INTEGER Timer::m_freq;
LONGLONG Timer::m_overhead;

Это необходимо для соблюдения правила единого определения.

person Pierre Fourgeaud    schedule 07.09.2013

struct Timer
{
.....
     static LARGE_INTEGER m_freq;  // This only declares a static member not definition
     static LONGLONG m_overhead;
};

Вам необходимо определить ниже статические члены Timer в файле .cpp:

LARGE_INTEGER Timer::m_freq;
LONGLONG Timer::m_overhead;
person billz    schedule 07.09.2013

Говоря языком непрофессионала, для тех, кто изучает эту тему, позвольте мне сказать это так. Вы объявили m_freq и m_overhead как static, что означает, что где-то в файле реализации (.cpp), который включает timer.h, вам нужно определить значения этих членов, как указано в @billz. Единица перевода, о которой упоминает @Pierre Fourgeaud, состоит из файла cpp и заголовков, которые он включает. Пример инициализации будет

В main.cpp:

...
int b[MAXNUM];
int c[MAXNUM];

LARGE_INTEGER m_freq = {0};  // Define them outside of all functions
LONGLONG m_overhead = {0};

int _tmain(int argc, _TCHAR* argv[])
{
    ...
    return 0;
}

Это позволит вам пройти две ошибки, которые вы видите.

person jmstoker    schedule 07.09.2013