带有 C 库的 QtCreator 中的链接器问题

Linker problem in QtCreator with C library

我有一个结构如下的项目:

3rd_party
  - heatmap.c
  - heatmap.h
  - lodepng.cpp
  - lodepng.h
CMakeLists.txt
data.cpp
data.hpp
main.cpp

当运行项目出现以下错误:

error: Undefined symbols for architecture x86_64:
  "_heatmap_add_weighted_point", referenced from:
      Data::plotImage(int, int, std::__1::vector<short, std::__1::allocator<short> > const&, std::__1::vector<Spherical, std::__1::allocator<Spherical> > const&, int) in data.cpp.o
  "_heatmap_free", referenced from:
      Data::plotImage(int, int, std::__1::vector<short, std::__1::allocator<short> > const&, std::__1::vector<Spherical, std::__1::allocator<Spherical> > const&, int) in data.cpp.o
  "_heatmap_new", referenced from:
      Data::plotImage(int, int, std::__1::vector<short, std::__1::allocator<short> > const&, std::__1::vector<Spherical, std::__1::allocator<Spherical> > const&, int) in data.cpp.o
  "_heatmap_render_default_to", referenced from:
      Data::plotImage(int, int, std::__1::vector<short, std::__1::allocator<short> > const&, std::__1::vector<Spherical, std::__1::allocator<Spherical> > const&, int) in data.cpp.o

我的data.cpp的一部分是:

#include "data.hpp"
#include <fstream>
#include <vector>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <array>
#include "3rd_party/heatmap.h"
/**
 * Create the heatmap PNG file,  suing the package in https://github.com/lucasb-eyer/libheatmap
 * @param Nx Number of columns of data.
 * @param Ny Number of rows of data.
 * @param image Array with the data to be converted to PNG.
 * @param counter To be included in the filename to distinguish between pictures.
 */
void Data::plotImage(int Nx, int Ny, const std::vector<short int>& image, const std::vector<Spherical> &sph, int counter){
    heatmap_t* hm = heatmap_new(Nx, Ny); // auxiliar function
    heatmap_add_weighted_point(hm, aprox_column, aprox_row, value); 
}

heatmap.cheatmap.h 复制自 https://github.com/lucasb-eyer/libheatmap

我的项目在 Visual Studio Code 中构建但未使用 QtCreator 我的 CMakeLists.txt:

cmake_minimum_required(VERSION 3.5)

project(trial LANGUAGES CXX)
set(ANDROID_NDK_ROOT "/Users/hectoresteban/Documents/C++/Qt/android-ndk-r21d")

set(CMAKE_INCLUDE_CURRENT_DIR ON)

set(CMAKE_AUTOUIC ON)
set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
# search for pkg-config
include (FindPkgConfig)
if (NOT PKG_CONFIG_FOUND)
    message (FATAL_ERROR "pkg-config not found")
endif ()

find_package(Qt5 COMPONENTS Core LinguistTools REQUIRED)

set(TS_FILES trial_en_DE.ts)

add_executable(trial
  main.cpp
  ${TS_FILES}
  data.cpp
  3rd_party/lodepng.cpp
  3rd_party/heatmap.c
)
target_link_libraries(trial Qt5::Core)

改变

project(trial LANGUAGES CXX)

project(trial LANGUAGES C CXX)

或者根本不指定语言:

project(trial)

或者,您可以将其单独构建为一个库,然后 link 将其添加到您的目标可执行文件中:

add_library(heatmap 
    3rd_party/heatmap.h
    3rd_party/heatmap.c
)

#...

target_link_libraries(trial Qt5::Core heatmap)