2016-11-22 6 views
0

Недавно я начал новый проект на C++. Проблема в том, что когда я пытаюсь скомпилировать его, я получаю ошибку связывания. Сегодня я провел весь день, пытаясь отладить его, но на самом деле я не нашел хорошего решения нигде. Если кто-то может помочь с этим, это будет потрясающе. Я использую Mac Sierra.Символ (ы) не найдены для архитектуры x86_64 - Cmake - Mac sierra

parsing/methylation.h

#ifndef EPIRL_METHYLATION_H 
#define EPIRL_METHYLATION_H 

#include <stdio.h> 
#include <iostream> 
#include <fstream> 
#include <vector> 
#include <sstream> 

using namespace std; 

namespace methylation { 
    struct MethLine { 
     string chr; 
     int coord; 
     char strand; 
     int methylated; 
     int un_methylated; 
     string context; 
     string tag; 
    }; 

    string calculateMethylationByContext(
      MethLine m_input[], int length, 
      int window_start, int window_end, int threshold); 

    void calculateMethylation(
     const istream &methylation_stream, 
     const istream &coordinate_stream, 
     const ostream &output_stream 
    ); 
} 

#endif //EPIRL_METHYLATION_H 

parsing/methylation.cpp

#include "methylation.h" 

namespace methylation { 
    string calculateMethylationByContext(
      MethLine m_input[], int length, 
      int window_start, int window_end, int threshold) { 
// rest of the code ... 
    } 
} 

main.cpp

#include <iostream> 
#include <fstream> 
#include "parsing/methylation.h" 

using namespace std; 

int main(int argc, char **argv) { 
    if (argc != 4) { 
     cout << "Invalid number of arguments..." << endl; 
     return 1; 
    } 

    char *methylation_file = argv[1]; 
    char *coordinate_file = argv[2]; 
    char *output_file = argv[3]; 

    ifstream methylation_file_stream(methylation_file, ios::binary); 
    ifstream coordinate_file_stream(coordinate_file, ios::binary); 
    ofstream output_file_stream(output_file, ios::binary); 

    methylation::calculateMethylation(methylation_file_stream, 
         coordinate_file_stream, output_file_stream); 
    methylation_file_stream.close(); 
    coordinate_file_stream.close(); 
    output_file_stream.close(); 

    return 0; 
} 

Я использую CLion для моего кодирования. Когда я пытаюсь построить его, моя команда CMake работает отлично, но когда я нажмите кнопку «сделать», я получаю следующее сообщение об ошибке:

Undefined symbols for architecture x86_64: 
    "methylation::calculateMethylation(std::__1::basic_istream<char, std::__1::char_traits<char> > const&, std::__1::basic_istream<char, std::__1::char_traits<char> > const&, std::__1::basic_ostream<char, std::__1::char_traits<char> > const&)", referenced from: 
     _main in main.cpp.o 
ld: symbol(s) not found for architecture x86_64 
clang: error: linker command failed with exit code 1 (use -v to see invocation) 
make[3]: *** [src] Error 1 
make[2]: *** [CMakeFiles/src.dir/all] Error 2 
make[1]: *** [CMakeFiles/src.dir/rule] Error 2 
make: *** [src] Error 2 

мой CMakeLists.txt файл выглядит следующим образом:

cmake_minimum_required(VERSION 3.6) 
project(src) 

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") 

set(SOURCE_FILES 
    parsing/methylation.cpp 
    parsing/methylation.h 
    main.cpp) 

add_executable(src ${SOURCE_FILES}) 

Когда я запускаю команду CMake, мой выход заключается в следующем:

-- The C compiler identification is AppleClang 8.0.0.8000042 
-- The CXX compiler identification is AppleClang 8.0.0.8000042 
-- Check for working C compiler: /Library/Developer/CommandLineTools/usr/bin/cc 
-- Check for working C compiler: /Library/Developer/CommandLineTools/usr/bin/cc -- works 
-- Detecting C compiler ABI info 
-- Detecting C compiler ABI info - done 
-- Detecting C compile features 
-- Detecting C compile features - done 
-- Check for working CXX compiler: /Library/Developer/CommandLineTools/usr/bin/c++ 
-- Check for working CXX compiler: /Library/Developer/CommandLineTools/usr/bin/c++ -- works 
-- Detecting CXX compiler ABI info 
-- Detecting CXX compiler ABI info - done 
-- Detecting CXX compile features 
-- Detecting CXX compile features - done 
-- Configuring done 
-- Generating done 
-- Build files have been written to: /Users/sztankatt/Documents/University/PartIII/Project/epiRL/src 
+0

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

+0

Я не вижу ** определения ** 'расчетMethylation' в коде, который вы предоставляете; в 'parsing/methylation.h' есть только * объявление * этой функции. – Tsyvarev

+0

Вы показываете материал, относящийся к 'calculateMethylationByContext', но ваша ошибка связана с' calculateMethylation'. Где вы определили эту функцию? – nos

ответ

0

Дважды проверьте, какой компилятор автоматически обнаруживает CMake. Можете ли вы опубликовать, что CMAKE сообщает вам, когда вы изначально запускаете CMAKE?

This may be a hint for your problem, too

+0

Эй! Просто опубликовал вывод моей команды cmake. Интересно, когда я копирую содержимое файла methylation.cpp в файл main.cpp, код компилируется без каких-либо ошибок. Кажется, что связь не работает должным образом. – tomooka

+0

Вы можете проверить, что происходит, когда вы пытаетесь следующее: Cmake -DCMAKE_C_COMPILER =/USR/бен/ССАГПЗ -DCMAKE_CXX_COMPILER =/USR/бен/г ++ –

+0

Точно такая же ошибка :( – tomooka

0

Ваш CMakeLists.txt прекрасно.

Как @ thomas-matthews @tsyvarev @nos указал в своих комментариях, в вашем примере кода отсутствует определение/реализация methylation::calculateMethylation(). То, что вы видите, - ожидаемая неудача с Apple/clang в этой ситуации.

❯ make 
[ 33%] Building CXX object CMakeFiles/src.dir/parsing/methylation.cpp.o 
/Users/nega/foo/parsing/methylation.cpp:8:5: warning: control reaches end of non-void function [-Wreturn-type] 
    } 
    ^
1 warning generated. 
[ 66%] Building CXX object CMakeFiles/src.dir/main.cpp.o 
[100%] Linking CXX executable src 
Undefined symbols for architecture x86_64: 
    "methylation::calculateMethylation(std::__1::basic_istream<char, std::__1::char_traits<char> > const&, std::__1::basic_istream<char, std::__1::char_traits<char> > const&, std::__1::basic_ostream<char, std::__1::char_traits<char> > const&)", referenced from: 
     _main in main.cpp.o 
ld: symbol(s) not found for architecture x86_64 
clang: error: linker command failed with exit code 1 (use -v to see invocation) 
make[2]: *** [src] Error 1 
make[1]: *** [CMakeFiles/src.dir/all] Error 2 
make: *** [all] Error 2 

Добавление фиктивной реализации или закомментировать вызов в вашем main.cpp, позволит make успешно завершить.

Если у вас есть правильное выполнение

Давайте предположим, что у вас есть реализацию methylation::calculateMethylation() в коде (возможно в другом файле). Первый шаг в отладке ошибок сборки в CMake, сгенерированном Makefiles, должен выполняться с переменной make VERBOSE, установленной на истинное значение, то есть: make VERBOSE=1.

❯ make VERBOSE=1 
/usr/local/Cellar/cmake/3.7.0/bin/cmake -H/Users/nega/foo -B/Users/nega/foo/build --check-build-system CMakeFiles/Makefile.cmake 0 
/usr/local/Cellar/cmake/3.7.0/bin/cmake -E cmake_progress_start /Users/nega/foo/build/CMakeFiles /Users/nega/foo/build/CMakeFiles/progress.marks 
/Applications/Xcode.app/Contents/Developer/usr/bin/make -f CMakeFiles/Makefile2 all 
/Applications/Xcode.app/Contents/Developer/usr/bin/make -f CMakeFiles/src.dir/build.make CMakeFiles/src.dir/depend 
cd /Users/nega/foo/build && /usr/local/Cellar/cmake/3.7.0/bin/cmake -E cmake_depends "Unix Makefiles" /Users/nega/foo /Users/nega/foo /Users/nega/foo/build /Users/nega/foo/build /Users/nega/foo/build/CMakeFiles/src.dir/DependInfo.cmake --color= 
/Applications/Xcode.app/Contents/Developer/usr/bin/make -f CMakeFiles/src.dir/build.make CMakeFiles/src.dir/build 
[ 33%] Building CXX object CMakeFiles/src.dir/parsing/methylation.cpp.o 
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/c++  -std=gnu++11 -o CMakeFiles/src.dir/parsing/methylation.cpp.o -c /Users/nega/foo/parsing/methylation.cpp 
/Users/nega/foo/parsing/methylation.cpp:8:5: warning: control reaches end of non-void function [-Wreturn-type] 
    } 
    ^
1 warning generated. 
[ 66%] Building CXX object CMakeFiles/src.dir/main.cpp.o 
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/c++  -std=gnu++11 -o CMakeFiles/src.dir/main.cpp.o -c /Users/nega/foo/main.cpp 
[100%] Linking CXX executable src 
/usr/local/Cellar/cmake/3.7.0/bin/cmake -E cmake_link_script CMakeFiles/src.dir/link.txt --verbose=1 
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/c++ -Wl,-search_paths_first -Wl,-headerpad_max_install_names CMakeFiles/src.dir/parsing/methylation.cpp.o CMakeFiles/src.dir/main.cpp.o -o src 
Undefined symbols for architecture x86_64: 
    "methylation::calculateMethylation(std::__1::basic_istream<char, std::__1::char_traits<char> > const&, std::__1::basic_istream<char, std::__1::char_traits<char> > const&, std::__1::basic_ostream<char, std::__1::char_traits<char> > const&)", referenced from: 
     _main in main.cpp.o 
ld: symbol(s) not found for architecture x86_64 
clang: error: linker command failed with exit code 1 (use -v to see invocation) 
make[2]: *** [src] Error 1 
make[1]: *** [CMakeFiles/src.dir/all] Error 2 
make: *** [all] Error 2 

Теперь вы можете посмотреть шаг ссылки и посмотреть, нет ли у вас предметов; возможно, библиотеку или объектный файл.Если да, то теперь вы знаете, чтобы вернуться и добавить его в CMakeLists.txt

Резюме

Первый шаг в отладке неожиданных сбоев сборки с CMake генерируемой Makefiles является запуск:

❯ make VERBOSE=1 

Это даст вы понимаете, что делает CMake за кулисами.

Смежные вопросы