链接CMake时出现未定义的参考错误

时间:2020-07-01 13:13:07

标签: c++ cmake portaudio opus

我试图在项目中包含portaudio和opus,但是每当我编译时,都会出现此错误

Scanning dependencies of target PeersChat
[ 50%] Building CXX object CMakeFiles/PeersChat.dir/main.cpp.obj
[100%] Linking CXX executable PeersChat.exe
CMakeFiles\PeersChat.dir/objects.a(main.cpp.obj): In function `main':
F:/Documents/Programming/Projects/PeersChat/main.cpp:13: undefined reference to `opus_encoder_create'
collect2.exe: error: ld returned 1 exit status
mingw32-make.exe[3]: *** [CMakeFiles\PeersChat.dir\build.make:86: PeersChat.exe] Error 1
mingw32-make.exe[2]: *** [CMakeFiles\Makefile2:75: CMakeFiles/PeersChat.dir/all] Error 2
mingw32-make.exe[1]: *** [CMakeFiles\Makefile2:82: CMakeFiles/PeersChat.dir/rule] Error 2
mingw32-make.exe: *** [Makefile:117: PeersChat] Error 2

这是我的main.cpp

#include <iostream>
#include <opus.h>

int main() {

    opus_int32 sampleRate = 8000;
    int channels = 2;

    int error;

    OpusEncoder *enc;
    enc = opus_encoder_create(sampleRate, channels, OPUS_APPLICATION_VOIP, &error);

    return 0;
}

编辑 我目前有这是我的cmake

cmake_minimum_required(VERSION 3.16)
project(PeersChat)

set(CMAKE_CXX_STANDARD 17)

# Opus Library
add_library(opus STATIC IMPORTED GLOBAL)
set_target_properties(opus PROPERTIES IMPORTED_LOCATION "F:/Documents/Programming/Libraries/opus")

add_executable(PeersChat main.cpp)
target_link_libraries(PeersChat opus)

现在出现此错误

fatal error: opus.h: No such file or directory
 #include <opus.h>
          ^~~~~~~~
compilation terminated.
mingw32-make.exe[3]: *** [CMakeFiles\PeersChat.dir\build.make:62: CMakeFiles/PeersChat.dir/main.cpp.obj] Error 1
mingw32-make.exe[2]: *** [CMakeFiles\Makefile2:75: CMakeFiles/PeersChat.dir/all] Error 2
mingw32-make.exe[1]: *** [CMakeFiles\Makefile2:82: CMakeFiles/PeersChat.dir/rule] Error 2
mingw32-make.exe: *** [Makefile:117: PeersChat] Error 2

1 个答案:

答案 0 :(得分:1)

您需要在CMakeLists.txt的末尾添加一行以将库链接到您的可执行文件:

target_link_libraries (PeersChat PRIVATE <the_libraries_to_link>)