Clion无法定义x86_64架构的符号

6

我的代码在CodeLite中编译运行正常。然后我尝试在Clion中运行同样的代码,但是它给了我这个错误:

Scanning dependencies of target leastSquareFitting
[ 50%] Building CXX object CMakeFiles/leastSquareFitting.dir/main.cpp.o
[100%] Linking CXX executable leastSquareFitting
Undefined symbols for architecture x86_64:
  "printMatrix(Matrix)", referenced from:
      _main in main.cpp.o
  "constructMatrix(int, std::__1::vector<double, 
std::__1::allocator<double> >)", 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]: *** [leastSquareFitting] Error 1
make[2]: *** [CMakeFiles/leastSquareFitting.dir/all] Error 2
make[1]: *** [CMakeFiles/leastSquareFitting.dir/rule] Error 2
make: *** [leastSquareFitting] Error 2

我尝试在网上搜索这个错误,但是根据我找到的内容无法解决它。以下是我的代码:

main.cpp

#include "fullMatrix.h"
#include <cstdio>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
    vector<double> value = {1.0,2.0,3.0,4.0};
    Matrix m = constructMatrix(2, value);
    printMatrix(m);
    return 0;
}   

fullMatrix.cpp

#include "fullMatrix.h"
#include <iostream>
#include <vector>
#include "cmath"
#include <cstdio>
using namespace std;


Matrix constructMatrix(int size, vector<double> x) {
    //initiate variables of a matrix
    Matrix myMatrix;
    myMatrix.size = size;
    myMatrix.value = x;
    return myMatrix;
}

void printMatrix(Matrix matrix){
    // Loop through rows and columns to display all values
    for (int row = 0; row < matrix.size; row++) {
        for (int col = 0; col < matrix.size; col++) {
            cout <<matrix.value[col+row*matrix.size] << " ";
        }
        cout << endl;
    }
}

fullMatrix.h

#ifndef fullMatrix_h
#define fullMatrix_h
#include <vector>
using namespace std;

struct Matrix
{
    int size;
    vector<double> value;
};
Matrix constructMatrix(int size, vector<double> x);

void printMatrix(Matrix matrix);

#endif

我是一个CMake的新手,以下是CMakeLists.txt文件的内容:

cmake_minimum_required(VERSION 3.10)
project(leastSquareFitting)

set(CMAKE_CXX_STANDARD 11)

add_executable(leastSquareFitting main.cpp)

谢谢!非常感谢任何帮助!

我在主函数中添加了#include "fullMatrix.cpp"后它就可以工作了,有人能解释一下为什么吗?并且怎样才能正确地修复它呢?(希望只需更改Clion中的某些配置) - 小小程序猿
不要 #include cpp 文件,这些文件有函数的实现,当你在两个不同的文件中包含相同的 cpp 文件时,链接器会抱怨。相反,让 cmake 知道你需要它为你的程序编译和链接这两个文件。查看我的答案以了解如何做到这一点。 - Daniel
1个回答

9
将您的CMakeLists的最后一行更改为:
add_executable(leastSquareFitting main.cpp fullMatrix.cpp)

链接器告诉你的是它找不到包含函数 printMatrix 的已编译文件,如果你查看 cmake 的输出,你会发现 cmake 只编译了 main.cpp,但没有提到 fullMatrix.cpp:
Building CXX object CMakeFiles/leastSquareFitting.dir/main.cpp.o

它没有提到另一个文件的原因是你没有告诉它那个文件也是你的源文件之一。


非常感谢!问题已解决。 - 小小程序猿
如果有答案解决了你的问题,@小小程序猿 需要点击旁边的勾选标记来接受答案。 - xaxxon

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接