clang:错误:vscode上的链接器命令失败

时间:2017-05-26 07:25:47

标签: c++ c++11 visual-studio-code

我收到以下错误。我该如何解决?这是我第一次在vscode上编译多个源代码。

错误消息

Undefined symbols for architecture x86_64:
  "Vector::size()", referenced from:
      sqrt_sum(Vector&) in user-9f738c.o
  "Vector::operator[](int)", referenced from:
      sqrt_sum(Vector&) in user-9f738c.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

user.cpp

#include "Vector.h"
#include <cmath>

using namespace std;

double sqrt_sum(Vector& v)
{
    double sum = 0;
    for (int i = 0; i != v.size(); ++i)
        sum += sqrt(v[i]);
    return sum;
}

int main() {

}

Vector.h

class Vector
{
    public:
        Vector(int s);
        double& operator[](int i);
        int size();
    private:
        double* elem;
        int sz;
};

Vector.cpp

#include "Vector.h"

Vector::Vector(int s):elem {new double[s]}, sz{s} 
{
}

double& Vector::operator[](int i)
{
    return elem[i];
}

int Vector::size()
{
    return sz;
}

tasks.json

{
    "version": "0.1.0",
    "command": "g++",
    "isShellCommand": true,
    "args": ["-std=c++11", "-O2", "-g", "user.cpp"],
    "showOutput": "always"
}

更新1

添加Vector.cpp

后完成编译
{
    "version": "0.1.0",
    "command": "g++",
    "isShellCommand": true,
    "args": ["-std=c++11", "-O2", "-g", "user.cpp", "Vector.cpp"],
    "showOutput": "always"
}

更新2

似乎有效。谢谢大家!

user.cpp

#include <iostream>
#include <cmath>

#include "Vector.h"

using namespace std;

double sqrt_sum(Vector& v)
{
    double sum = 0;
    for (int i = 0; i != v.size(); ++i)
        sum += sqrt(v[i]);
    return sum;
}

int main() {
    Vector v(4);
    int sum = sqrt_sum(v);
    cout << sum << endl;
}

结果

$ ./a.out
-2147483648

0 个答案:

没有答案