error LNK2001: 无法解析的外部符号 "public: virtual struct QMetaObject const * __thiscall Widget::metaObject

来源:互联网 发布:java开源工作流框架 编辑:程序博客网 时间:2024/05/16 23:58

编写一个简单的给予QT的DEMO程序步骤大致如下:

下面开始编程:

A 编写 main.cpp

B 编写 hello.h

C 编写 hello.cpp

D 制作.ui文件,并生成ui_hello.h
    打开designer,拖入一个pushButton,一个label。保存为hello.ui。然后生成ui_hello.h,并添加到项目的源文件中。

  编译运行,则出现如下错误:
错误 1 error LNK2001: 无法解析的外部符号 "public: virtual struct QMetaObject const * __thiscall Widget::metaObject(void)const " (?metaObject@Widget@@UBEPBUQMetaObject@@XZ)
错误 2 error LNK2001: 无法解析的外部符号 "public: virtual void * __thiscall Widget::qt_metacast(char const *)" (?qt_metacast@Widget@@UAEPAXPBD@Z)
错误 3 error LNK2001: 无法解析的外部符号 "public: virtual int __thiscall Widget::qt_metacall(enum QMetaObject::Call,int,void * *)" (?qt_metacall@Widget@@UAEHW4Call@QMetaObject@@HPAPAX@Z)
错误 4 fatal error LNK1120: 3 个无法解析的外部命令  
   
    这是因为在源文件中没有添加上moc_hello.cpp文件。
    解决方法:右击hello.h,选择“自定义生成步骤”,“常规”
    命令行:moc.exe hello.h -o moc_hello.cpp
    输出:moc_hello.cpp
    附加依赖项:moc.exe hello.h
    确定,然后,右击hello.h,选择 “编译”,则在文件夹中生成moc_hello.cpp,再将其添加到源文件中。



    然后,运行程序,出现错误:
    错误  fatal error C1010: 在查找预编译头时遇到意外的文件结尾。是否忘记了向源中添加“#include "stdafx.h"”?
    则在moc_hello.cpp文件的开头添加上:#include "stdafx.h"。
    然后,再运行。仍然出现上面错误。这是因为当运行程序,又重新生成了moc_hello.cpp文件(这个新的文件的开头显然是没有#include "stdafx.h"),覆盖了已经修改过的文件。
    解决方法:右击hello.h,选择“自定义生成步骤”,“常规”
    清空“命令行” “输出” “附加依赖项” 里对应的内容。这样在运行程序时就不会再生成新的moc_hello.cpp文件了。然后确定。
 
    这样再次运行程序,可以成功运行。

对于上述的第二个错误可以直接在项目属性--》C/C++--》预编译头--》创建/使用预编译头改为不使用预编译头。就可以一劳永逸了,不用上述这么麻烦的方法了。
原创粉丝点击