Ошибка компоновщика c ++: неопределенные ссылки только в оптимизированной сборке

Я получаю ошибку компоновщика неопределенных ссылок только при связывании файлов оптимизированных объектов, нет при связывании файлов неоптимизированных объектов. Я не понимаю, в чем проблема или может быть.

Вот моя неоптимизированная сборка:

Building file: ../COMPASS.cpp
Invoking: GCC C++ Compiler
g++ -O0 -g3 -pg -Wall -c -fmessage-length=0 -Wno-sign-compare -fopenmp -MMD -MP -MF"COMPASS.d" -MT"COMPASS.d" -o"COMPASS.o" "../COMPASS.cpp"
Finished building: ../COMPASS.cpp

Building file: ../PSA.cpp
Invoking: GCC C++ Compiler
g++ -O0 -g3 -pg -Wall -c -fmessage-length=0 -Wno-sign-compare -fopenmp -MMD -MP -MF"PSA.d" -MT"PSA.d" -o"PSA.o" "../PSA.cpp"
Finished building: ../PSA.cpp

Building file: ../SAR.cpp
Invoking: GCC C++ Compiler
g++ -O0 -g3 -pg -Wall -c -fmessage-length=0 -Wno-sign-compare -fopenmp -MMD -MP -MF"SAR.d" -MT"SAR.d" -o"SAR.o" "../SAR.cpp"
Finished building: ../SAR.cpp

Building file: ../constraints.cpp
Invoking: GCC C++ Compiler
g++ -O0 -g3 -pg -Wall -c -fmessage-length=0 -Wno-sign-compare -fopenmp -MMD -MP -MF"constraints.d" -MT"constraints.d" -o"constraints.o" "../constraints.cpp"
Finished building: ../constraints.cpp

Building file: ../genetic.cpp
Invoking: GCC C++ Compiler
g++ -O0 -g3 -pg -Wall -c -fmessage-length=0 -Wno-sign-compare -fopenmp -MMD -MP -MF"genetic.d" -MT"genetic.d" -o"genetic.o" "../genetic.cpp"
Finished building: ../genetic.cpp

Building file: ../globals.cpp
Invoking: GCC C++ Compiler
g++ -O0 -g3 -pg -Wall -c -fmessage-length=0 -Wno-sign-compare -fopenmp -MMD -MP -MF"globals.d" -MT"globals.d" -o"globals.o" "../globals.cpp"
Finished building: ../globals.cpp

Building file: ../logging.cpp
Invoking: GCC C++ Compiler
g++ -O0 -g3 -pg -Wall -c -fmessage-length=0 -Wno-sign-compare -fopenmp -MMD -MP -MF"logging.d" -MT"logging.d" -o"logging.o" "../logging.cpp"
Finished building: ../logging.cpp

Building file: ../main.cpp
Invoking: GCC C++ Compiler
g++ -O0 -g3 -pg -Wall -c -fmessage-length=0 -Wno-sign-compare -fopenmp -MMD -MP -MF"main.d" -MT"main.d" -o"main.o" "../main.cpp"
Finished building: ../main.cpp

Building file: ../sampling.cpp
Invoking: GCC C++ Compiler
g++ -O0 -g3 -pg -Wall -c -fmessage-length=0 -Wno-sign-compare -fopenmp -MMD -MP -MF"sampling.d" -MT"sampling.d" -o"sampling.o" "../sampling.cpp"
Finished building: ../sampling.cpp

Building file: ../simulation1.cpp
Invoking: GCC C++ Compiler
g++ -O0 -g3 -pg -Wall -c -fmessage-length=0 -Wno-sign-compare -fopenmp -MMD -MP -MF"simulation1.d" -MT"simulation1.d" -o"simulation1.o" "../simulation1.cpp"
../globals.h: At global scope:
../globals.h:43: warning: inline function 'double showDecimals(const double&, const int&)' used but never defined
Finished building: ../simulation1.cpp

Building file: ../test_function.cpp
Invoking: GCC C++ Compiler
g++ -O0 -g3 -pg -Wall -c -fmessage-length=0 -Wno-sign-compare -fopenmp -MMD -MP -MF"test_function.d" -MT"test_function.d" -o"test_function.o" "../test_function.cpp"
Finished building: ../test_function.cpp

Building target: pc2
Invoking: GCC C++ Linker
g++ -pg -fopenmp -pg -o"pc2"  ./COMPASS.o ./PSA.o ./SAR.o ./constraints.o ./genetic.o ./globals.o ./logging.o ./main.o ./sampling.o ./simulation1.o ./test_function.o   
Finished building target: pc2

Вот моя оптимизированная сборка:

Building file: ../COMPASS.cpp
Invoking: GCC C++ Compiler
g++ -O3 -Wall -c -fmessage-length=0 -Wno-sign-compare -fopenmp -MMD -MP -MF"COMPASS.d" -MT"COMPASS.d" -o"COMPASS.o" "../COMPASS.cpp"
Finished building: ../COMPASS.cpp

Building file: ../PSA.cpp
Invoking: GCC C++ Compiler
g++ -O3 -Wall -c -fmessage-length=0 -Wno-sign-compare -fopenmp -MMD -MP -MF"PSA.d" -MT"PSA.d" -o"PSA.o" "../PSA.cpp"
Finished building: ../PSA.cpp

Building file: ../SAR.cpp
Invoking: GCC C++ Compiler
g++ -O3 -Wall -c -fmessage-length=0 -Wno-sign-compare -fopenmp -MMD -MP -MF"SAR.d" -MT"SAR.d" -o"SAR.o" "../SAR.cpp"
Finished building: ../SAR.cpp

Building file: ../constraints.cpp
Invoking: GCC C++ Compiler
g++ -O3 -Wall -c -fmessage-length=0 -Wno-sign-compare -fopenmp -MMD -MP -MF"constraints.d" -MT"constraints.d" -o"constraints.o" "../constraints.cpp"
Finished building: ../constraints.cpp

Building file: ../genetic.cpp
Invoking: GCC C++ Compiler
g++ -O3 -Wall -c -fmessage-length=0 -Wno-sign-compare -fopenmp -MMD -MP -MF"genetic.d" -MT"genetic.d" -o"genetic.o" "../genetic.cpp"
Finished building: ../genetic.cpp

Building file: ../globals.cpp
Invoking: GCC C++ Compiler
g++ -O3 -Wall -c -fmessage-length=0 -Wno-sign-compare -fopenmp -MMD -MP -MF"globals.d" -MT"globals.d" -o"globals.o" "../globals.cpp"
Finished building: ../globals.cpp

Building file: ../logging.cpp
Invoking: GCC C++ Compiler
g++ -O3 -Wall -c -fmessage-length=0 -Wno-sign-compare -fopenmp -MMD -MP -MF"logging.d" -MT"logging.d" -o"logging.o" "../logging.cpp"
Finished building: ../logging.cpp

Building file: ../main.cpp
Invoking: GCC C++ Compiler
g++ -O3 -Wall -c -fmessage-length=0 -Wno-sign-compare -fopenmp -MMD -MP -MF"main.d" -MT"main.d" -o"main.o" "../main.cpp"
Finished building: ../main.cpp

Building file: ../sampling.cpp
Invoking: GCC C++ Compiler
g++ -O3 -Wall -c -fmessage-length=0 -Wno-sign-compare -fopenmp -MMD -MP -MF"sampling.d" -MT"sampling.d" -o"sampling.o" "../sampling.cpp"
Finished building: ../sampling.cpp

Building file: ../simulation1.cpp
Invoking: GCC C++ Compiler
g++ -O3 -Wall -c -fmessage-length=0 -Wno-sign-compare -fopenmp -MMD -MP -MF"simulation1.d" -MT"simulation1.d" -o"simulation1.o" "../simulation1.cpp"
../globals.h: At global scope:
../globals.h:43: warning: inline function 'double showDecimals(const double&, const int&)' used but never defined
Finished building: ../simulation1.cpp

Building file: ../test_function.cpp
Invoking: GCC C++ Compiler
g++ -O3 -Wall -c -fmessage-length=0 -Wno-sign-compare -fopenmp -MMD -MP -MF"test_function.d" -MT"test_function.d" -o"test_function.o" "../test_function.cpp"
Finished building: ../test_function.cpp

Building target: pc2
Invoking: GCC C++ Linker
g++ -fopenmp -o"pc2"  ./COMPASS.o ./PSA.o ./SAR.o ./constraints.o ./genetic.o ./globals.o ./logging.o ./main.o ./sampling.o ./simulation1.o ./test_function.o   
./logging.o: In function `LOG_COMPASS_display_points_MATLAB(int const&, VisitedSet&)':
logging.cpp:(.text+0x686): undefined reference to `VisitedSet::getSize()'
collect2: ld returned 1 exit status
make: *** [pc2] Error 1
make: Leaving directory `/home/djunderw/ncsu/workspace/pc2/release'

Любые идеи?

[ИСПРАВЛЕННАЯ ПРОБЛЕМА С ФУНКЦИЕЙ showDecimals ()]

Файл COMPASS.h включает этот шаблон класса:

template<class T> class VisitedSet {
public:
    VisitedSet(const T& soln); 
    int getSize();
    void addSolution(const T& soln);
    void evaluate();
    void sample(const int& numNewSolutions, Constraints& space);
    void CSBiased_generateDistribution();
    void constructMPA(Constraints& space);
    vector<T> vec;
    double bestValue;
    int bestIndex;

    /* used to implement biased coordinate sampling */
    double CSBiased_coefficient;
    vector< vector<double> > lastSampledPoints;
    vector<int> lastSampledPointsIndex;
    vector< vector<double> > newSampledPoints;
    vector<int> newSampledPointsIndex;
    vector<double> CSBiased_distribution;

private:
    int iteration;
    int dimension; 
    int SAR(); // simulation allocation rule
};

И COMPASS.cpp включает следующий код:

template<class T>
int VisitedSet<T>::getSize() {
    return vec.size();
}

Файлы logging.cpp включают следующий код:

#include "COMPASS.h"
void LOG_COMPASS_display_points_MATLAB(const int& iteration, VisitedSet<Policy>& visited) {
    cout << "points{"<<iteration+1<<"} = [\n"
         << visited.vec[visited.bestIndex].x[0] << "\t" <<     visited.vec[visited.bestIndex].x[1] << "\t" << visited.vec[visited.bestIndex].meanQALY() << ";" << endl;
for(int i=0; i<visited.getSize(); i++) {
    if(i != visited.bestIndex)
        cout << visited.vec[i].x[0] << "\t" << visited.vec[i].x[1] << "\t" << visited.vec[i].meanQALY() << ";" << endl;
}
cout << "];\n";
}

person synaptik    schedule 03.09.2012    source источник
comment
Может быть, вы в спешке забыли подготовить минимальный кейс и опубликовать код? ;-)   -  person Michael Krelin - hacker    schedule 03.09.2012
comment
Покажи код. Подозрительно, что вы получаете предупреждение о showDecimals ранее в журнале, а затем получаете ошибку компоновщика, которая относится к ней позже, чего это стоит.   -  person Stuart Golodetz    schedule 03.09.2012
comment
Может быть, вы не реализовали showDecimals(double const&, int const&)?   -  person Luchian Grigore    schedule 03.09.2012
comment
@StuartGolodetz Извините, я решил проблему showDecimals. У меня был встроенный прототип в файле заголовка и встроенное тело функции в файле кода. Я просто помещаю встроенное тело в файл заголовка, и теперь прототипа, отделенного от тела функции, больше нет. Теперь эта проблема решена. Я опубликую более подробную информацию об оставшейся проблеме сейчас ...   -  person synaptik    schedule 03.09.2012
comment
Так где же определяется VisitedSet::getSize()?   -  person aschepler    schedule 03.09.2012
comment
@aschepler Я только что обновил свой пост, чтобы показать фактическое определение и объявление VisitedSet :: getSize ().   -  person synaptik    schedule 03.09.2012
comment
@veer Нет, потому что Policy - это имя класса, к которому я хочу применить шаблон VisitedSet. (Кроме того, нет проблем сделать это в другом месте.)   -  person synaptik    schedule 03.09.2012


Ответы (1)


int VisitedSet<T>::getSize() - это шаблонная функция, поэтому ее определение должно быть в заголовочном файле, таком как COMPASS.h, а не в COMPASS.cpp.

Вот почему: http://www.parashift.com/c++-faq/templates-defn-vs-decl.html.

person aschepler    schedule 03.09.2012
comment
В качестве побочного момента интересно отметить, что (насколько я помню) вы должны быть осторожны со специализациями шаблонов - частичные специализации шаблона (которые все еще зависят от параметра шаблона) должны идти в заголовке, но полные специализации шаблона (которых нет) должны помещаться в .cpp файл. - person Stuart Golodetz; 04.09.2012