我正在尝试使用CMake运行Qt5教程的简单计算器示例。我得到的错误是
[ 25%] Automatic moc and uic for target calculator
[ 25%] Built target calculator_automoc
Scanning dependencies of target calculator
[ 50%] Building CXX object CMakeFiles/calculator.dir/main.cpp.o
[ 75%] Linking CXX executable calculator
CMakeFiles/calculator.dir/main.cpp.o: In function `main':
main.cpp:(.text+0x45): undefined reference to `Calculator::Calculator(QWidget*)'
CMakeFiles/calculator.dir/main.cpp.o: In function `Calculator::~Calculator()':
main.cpp:(.text._ZN10CalculatorD2Ev[_ZN10CalculatorD5Ev]+0xf): undefined reference to `vtable for Calculator'
main.cpp:(.text._ZN10CalculatorD2Ev[_ZN10CalculatorD5Ev]+0x21): undefined reference to `vtable for Calculator'
collect2: error: ld returned 1 exit status
CMakeFiles/calculator.dir/build.make:123: recipe for target 'calculator' failed
make[3]: *** [calculator] Error 1
CMakeFiles/Makefile2:67: recipe for target 'CMakeFiles/calculator.dir/all' failed
make[2]: *** [CMakeFiles/calculator.dir/all] Error 2
CMakeFiles/Makefile2:79: recipe for target 'CMakeFiles/calculator.dir/rule' failed
make[1]: *** [CMakeFiles/calculator.dir/rule] Error 2
Makefile:118: recipe for target 'calculator' failed
make: *** [calculator] Error 2
然后我找到this并将CMAKE_AUTOMOC设置为ON,但它没有帮助。这似乎是一个基本的CMakeLists.txt错误,但我几天都无法克服。
以下是我的文件:
的CMakeLists.txt
cmake_minimum_required(VERSION 2.8.11)
set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTOUIC ON)
# Find includes in corresponding build directories
set(CMAKE_INCLUDE_CURRENT_DIR ON)
# Tell CMake to create the calculator executable
add_executable(calculator main.cpp)
project(calculator)
SET(CMAKE_PREFIX_PATH $ENV{HOME}/software/Qt5.7.0/5.7/gcc_64)
# Find the QtWidgets library
find_package(Qt5Widgets)
# Use the Widgets module from Qt 5.
target_link_libraries(calculator Qt5::Widgets)
的main.cpp
#include <QApplication>
#include "calculator.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
Calculator calc;
calc.show();
return app.exec();
}
calculator.h
#ifndef CALCULATOR_H
#define CALCULATOR_H
#include <QWidget>
class Calculator : public QWidget
{
Q_OBJECT
public:
Calculator(QWidget *parent = 0);
};
#endif
calculator.cpp
#include <QtGui>
#include <math.h>
#include "calculator.h"
Calculator::Calculator(QWidget *parent)
: QWidget(parent)
{
QGridLayout *mainLayout = new QGridLayout;
setWindowTitle(tr("Calculator"));
}
感谢您的帮助!
答案 0 :(得分:1)
CMakeLists.txt
中的这一行:
add_executable(calculator main.cpp) #calculator.cpp button.cpp)
可能您没有意识到这一点,但#
指定了评论。因此,cmake未设置为将calculator.cpp
或button.cpp
编译或链接到您的可执行文件中。