文件包含错误(C ++):未定义引用______ [英] File inclusion errors (C++): undefined reference to ______

查看:708
本文介绍了文件包含错误(C ++):未定义引用______的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当我编译包含用户定义的类的东西时,我得到这些编译错误总是看起来像: main.cpp:未定义的引用Complex :: Complex(double,double) code>

Whenever I compile something that #includes a user-defined class, I get these compilation errors that always look like: main.cpp: undefined reference to Complex::Complex(double, double)

我将问题缩减为一组三个非常裸的文件:main.cpp,例如Complex.h和Complex.cpp 。我仍然得到未定义的参考错误。我在Windows上的Code :: Blocks开发,但是在Ubuntu中使用g ++也是一样。为什么会发生这种情况?我试过在Code :: Blocks中的main.cpp之前构建Complex.cpp,我已经尝试过 g ++ main.cpp Complex.cpp 只需 g ++ main.cpp 。每次都有相同的错误。

I've reduced the problem to a set of three extremely bare files: main.cpp, and for example, Complex.h and Complex.cpp. I still get undefined reference errors. I'm developing in Code::Blocks on Windows but I get the same thing using g++ in Ubuntu. Why does this happen? I've tried building Complex.cpp before main.cpp in Code::Blocks, and I've tried g++ main.cpp Complex.cpp as much as I've tried just g++ main.cpp. Same errors every time.

/*======== main.cpp ========*/
#include "Complex.h"

int main()
{
    Complex A(1.0, 1.0);
    return 0;
}

/*======== Complex.h ========*/
#ifndef _COMPLEX_H
#define _COMPLEX_H

class Complex
{
    public:
    double x, y;
    Complex(double real, double imag);
};

#endif

/*======== Complex.cpp ========*/
#include "Complex.h"

Complex::Complex(double real, double imag)
{
    x = real;
    y = imag;
}

ed:现在我得到不同的错误,所以我必须做一些完全错误的事情。使用与上面相同的代码,我得到:

ed: now I get different errors so I must be doing something completely wrong. Using the same code as above, I get:

main.cpp: in function 'int main()':
main.cpp:5:5: error: 'Complex' was not declared in this scope
main.cpp:5:13: error: expected ';' before 'A'

这很奇怪。一切工作更早,当我有一个.cpp文件中的类,但这是坏习惯,所以我把我的类定义移动到.h文件,并保存在.cpp文件中的实现,现在没有什么工作。

This is bizarre. Everything worked earlier when I had the class in a .cpp file, but that's "bad practice" so I moved my class definitions into .h files and kept the implementation in .cpp files, and now nothing works.

推荐答案

这不是一个编译错误,它是一个链接错误。您需要确保将所有对象链接在一起。您可以通过以下几种方式完成此操作:

That's not a compilation error, it's a link error. You need to make sure to link all of your objects together. You can do that in a couple ways:

g++ main.cpp Complex.cpp

应该工作正常(当我尝试你的例子时,这里)。您也可以执行以下步骤:

Should work fine (and does here when I tried with your example). You can also do it in steps:

g++ -c main.cpp
g++ -c Complex.cpp
g++ main.o Complex.o

这篇关于文件包含错误(C ++):未定义引用______的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆