VS Code C ++ OOP在Mac OS High Sierra中不起作用

问题描述 投票:-1回答:1

大家好,我是vs代码的新手,我找不到使用面向对象编程的解决方案

当我创建一个.h文件来调用对象函数时,我得到一个错误

123MacBook-Pro-de-Rogerio: life DJMatrix $ cd "/ Users / DJMatrix / Documents / Classes / c ++ / life /" && g ++ main.cpp -o main && "/ Users / Dtrix / Documents / Classes / c ++ / life / "main
Undefined symbols for architecture x86_64:
  "Life :: tryAgain ()", referenced from:
      _main in main-ea3ce4.o
ld: symbol (s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Print

main.cpp:

#include <iostream>
#include "life.h"

using namespace std;

int main()
{
    Life life;
    life.tryAgain();
    return 0;
}

life.h:

#include <iostream>
using namespace std;

class Life
{
public:
    bool sucess;
  void tryAgain();
  void improve();
};

life.cpp:

#include "life.h"

void Life::tryAgain()
{
  cout << "Trying again!!!" << endl;
}

void Life::improve()
{
  cout << "Improve !!" << endl;
}
c++ macos oop visual-studio-code clang++
1个回答
1
投票

根据我从VSCode终端看到的信息,只有main.cpp正在被编译。当您生成最终的二进制文件时,life.cpp的目标文件未链接,这就是为什么它抱怨Life::tryAgain()符号丢失的原因。

这取决于您是手动调用编译器还是使用Makefile,还是让VSCode为您完成所有这些操作;无论compile命令应如下所示:

g++ -o main life.cpp main.cpp

© www.soinside.com 2019 - 2024. All rights reserved.