【问题标题】:Undefined reference constructor while compiling C++ code编译 C++ 代码时未定义的引用构造函数
【发布时间】:2017-03-17 02:19:48
【问题描述】:

当我尝试使用g++ main.cpp 编译三个 c++ 文件时收到以下错误。如果我将它们组合在一个文件中,它就可以工作。

main.cpp:(.text+0x10): undefined reference to `Time::Time()'

时间.cpp

#include <iostream>
#include "Time.h"
using namespace std;

Time::Time()
{
    a=5;
}

时间.h

#ifndef TIME_H
#define TIME_H

class Time {

public:
Time();
private:
int a;
};
#endif

main.cpp

#include <iostream>
#include "Time.h" 
using namespace std;


int main()
{
    Time t;
}

【问题讨论】:

标签: c++ g++ linker-errors undefined-reference


【解决方案1】:

您需要编译所有 CPP 文件,因为每个文件都是单独的compilation unit

g++ main.cpp Time.cpp -o main

有关阅读的更多信息

【讨论】:

  • 有捷径吗?如果我有超过 100 个文件怎么办?
  • 如果你有那么多文件,那么你必须创建一个makefile,否则你最终会一次又一次地编译一个文件。在 MSVC 或其他一些 IDE 中,只需创建一个新的解决方案/项目,IDE 将为您处理编译
  • 你可以使用 shell 扩展,例如g++ *.cpp -o main
猜你喜欢
  • 1970-01-01
  • 2011-02-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-14
  • 1970-01-01
相关资源
最近更新 更多