有人能解開我為什么會得到鏈接錯誤的奧秘,如果我只在我制作變數時,應該在模板引數中使用變數的地址const,constexpr或者static,而不是否則?
下面的代碼片段是一個更大專案的一部分,但我提取了完全相同的結構:
CMakeLists.txt
project(fun)
add_library(fun SHARED fun.cpp)
add_executable(main main.cpp)
target_link_libraries(main fun)
樂趣.cpp
#include "fun.h"
BlaaUser testBlaa(int)
{
return BlaaUser();
}
樂趣.h
#pragma once
#include "types.h"
extern BlaaUser testBlaa(int);
主檔案
#include "fun.h"
int main()
{
auto b = testBlaa(2);
}
型別.h
#pragma once
struct P
{
char n;
};
template<const P* S>
struct Blaa
{
Blaa() {}
char blaa{S->n};
};
//constexpr
//static
//const
P p{}; // <-- Here, right now it works. If I uncomment any of the specifiers, I get errors, see below
using BlaaUser = Blaa<&p>;
如果我添加任何型別的說明符,我會收到以下錯誤:
Scanning dependencies of target fun
[ 25%] Building CXX object CMakeFiles/fun.dir/fun.cpp.o
[ 50%] Linking CXX shared library libfun.so
[ 50%] Built target fun
Scanning dependencies of target main
[ 75%] Building CXX object CMakeFiles/main.dir/main.cpp.o
In file included from /home/fld/work/tmpl_test/main.cpp:1:
/home/fld/work/tmpl_test/fun.h:5:17: warning: ‘BlaaUser testBlaa(int)’ used but never defined
5 | extern BlaaUser testBlaa(int);
| ^~~~~~~~
[100%] Linking CXX executable main
/usr/bin/ld: CMakeFiles/main.dir/main.cpp.o: in function `main':
main.cpp:(.text 0x12): undefined reference to `testBlaa(int)'
collect2: error: ld returned 1 exit status
make[2]: *** [CMakeFiles/main.dir/build.make:104: main] Error 1
make[1]: *** [CMakeFiles/Makefile2:97: CMakeFiles/main.dir/all] Error 2
make: *** [Makefile:103: all] Error 2
我有點感覺它與物件的地址有關(根據標準:對于指向物件的指標,模板引數必須指定具有靜態存盤持續時間和鏈接的完整物件的地址(內部或外部))但我有點困惑,因為如果一切都放在一個檔案中一切正常,那么當它在庫中拆分時就會出現問題......
有沒有人有任何解釋?
uj5u.com熱心網友回復:
附加說明符(例如const, constexpr)使模板引數具有內部鏈接,從而使模板引數具有testBlaa(int)內部鏈接。如果你這樣做,它會起作用
extern const P p{}
對?也許為什么以下方法會獲得內部鏈接?類似?
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/467031.html
上一篇:從影像中裁剪和提取圖章
