【问题标题】:C++ Compilation error - Undefined referenceC++ 编译错误 - 未定义的引用
【发布时间】:2015-08-31 00:30:02
【问题描述】:

尝试在 cygwin 中编译以下简单代码时遇到了一些麻烦:

main.cpp:

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

using namespace std;

int main() {
    Point a;
    return 0;
}

Point.cpp:

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

using namespace std;

Point::Point() {
    cout << "Compile test" << endl;
}

点.h:

#ifndef POINT_H
#define POINT_H

class Point {
    public:
        Point();
};

#endif

制作文件:

CC=g++
CFLAGS=-c -Wall
LDFLAGS=
SOURCES=main.cpp Point.cpp
OBJECTS=$(SOURCES:.cpp=.o)
EXECUTABLE=test

all: $(SOURCES) $(EXECUTABLE)

$(EXECUTABLE): $(OBJECTS)
    $(CC) $(LDFLAGS) $(OBJECTS) -o $@

%.o : %.cpp
    $(CC) $(CFLAGS) -c $<

clean:
    rm -rf *.o core

当我尝试编译 main.cpp 时,我收到以下错误:

main.o:main.cpp:(.text+0x15): undefined reference to `Point::Point()'
main.o:main.cpp:(.text+0x15): relocation truncated to fit: R_X86_64_PC32 against undefined symbol `Point::Point()'

当我尝试编译 Point.cpp 时,我得到:

/usr/lib/gcc/x86_64-pc-cygwin/4.9.3/../../../../lib/libcygwin.a(libcmain.o): In function `main':
/usr/src/debug/cygwin-2.2.1-1/winsup/cygwin/lib/libcmain.c:39: undefined reference to `WinMain'
/usr/src/debug/cygwin-2.2.1-1/winsup/cygwin/lib/libcmain.c:39:(.text.startup+0x7f): relocation truncated to fit: R_X86_64_PC32 against undefined symbol `WinMain'

所有文件都在同一个目录中。我还应该注意,如果我不创建点对象,主类编译得非常好。有任何想法吗?非常感谢您的帮助,谢谢!

【问题讨论】:

  • 你没有声明 Point::Point 的类型
  • @stark 是构造函数,没有返回类型。
  • 您可以做的一件事是,不用向我们展示 make 文件,而是向我们展示使用“verbose”选项执行时的 make 输出,以便我们看到实际的命令行。
  • 所以我的假设是你的构建系统搞砸了,你实际上并没有编译Point.cpp。当您使用make VERBOSE=1 时,您可以通过查看控制台中打印的内容来检查您是否存在,更多信息请参见:stackoverflow.com/questions/5820303/…
  • 没关系,我已经编译好了!我只需要将makefile 中的EXECUTABLE=test 更改为EXECUTABLE=main。感谢克里斯的帮助,没有你就无法解决!

标签: c++ reference compilation cygwin undefined


【解决方案1】:

(从 cmets 转贴,因为这最终解决了它)

所以,我的假设是您的构建系统搞砸了,而您实际上并没有编译 Point.cpp

当您使用make VERBOSE=1 时,您可以通过查看控制台中打印的内容来检查您是否是,更多信息在这里:

How do I force make/gcc to show me the commands?

【讨论】:

    【解决方案2】:

    当我忘记链接的可执行文件名时,我得到了相同的未定义引用“WinMain”问题。

    g++ -o source1.o source2.o
    

    而不是

    g++ -o executable source1.o source2.o
    

    我没有在任何地方找到我的问题的答案,所以我希望它可以帮助...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-25
      • 1970-01-01
      • 2011-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多