引入MiniAudio库编译时出现多重定义错误,如何解决?
解决MiniAudio库引入时的多重定义错误
代码结构
player.h
#ifndef PLAYER_H #define PLAYER_H #define MINIAUDIO_IMPLEMENTATION #include "miniaudio.h" class Player { ... } #endif
main.h
#ifndef MAIN_H #define MAIN_H #include "player.h" class Application { ... } #endif
player.cpp
#include "main.h" void Application::whateverFunc() { ... }
编译报错信息
player.cpp:(.text+0x7d330): multiple definition of `drwav_init_file_w'; obj/main.o:main.cpp:(.text+0x7d88e): first defined here /usr/bin/ld: obj/player.o: in function `ma_wav_init_memory(void const*, unsigned long, ma_decoding_backend_config const*, ma_allocation_callbacks const*, ma_wav*)': player.cpp:(.text+0x52c24): multiple definition of `ma_wav_init_memory(void const*, unsigned long, ma_decoding_backend_config const*, ma_allocation_callbacks const*, ma_wav*)'; obj/main.o:main.cpp:(.text+0x530e5): first defined here /usr/bin/ld: obj/player.o: in function `drwav_init_memory': etc....
解决方法
问题出在MINIAUDIO_IMPLEMENTATION宏的使用上:这个宏的作用是让MiniAudio的头文件生成具体的实现代码。你现在把它放在player.h里,而player.h被多个源文件(比如main.cpp、player.cpp)包含,导致同一份实现代码被多次编译,链接时就会触发多重定义错误。
按以下步骤修改:
- 从
player.h中删掉#define MINIAUDIO_IMPLEMENTATION,修改后的player.h如下:#ifndef PLAYER_H #define PLAYER_H #include "miniaudio.h" class Player { ... } #endif - 找唯一一个源文件(比如
player.cpp),在包含任何头文件之前先定义这个宏,再包含miniaudio.h。修改后的player.cpp:#define MINIAUDIO_IMPLEMENTATION #include "miniaudio.h" #include "main.h" void Application::whateverFunc() { ... }
这样就能保证MiniAudio的实现代码只被编译一次,链接时就不会再报错了。
内容的提问来源于stack exchange,提问作者Duddy67
相关产品推荐
相关产品推荐

