我正在用Code::Blocks编写一个c++包供以后使用。
项目结构如下所示:
cNormal
cNormal.cdp
src
main.cpp # for testing purpose
cnormal_defs.h # important compiler definitions
cnormal_storage.h # includes all .h files from "./storage"
storage
cnarray.h
cnarray.cpp
cnstack.h
cnstack.cpp
bin
obj
cnormal_storage.h:
// cnormal_storage.h
// *****************************************************************
// Includes all necessary headers for the cNormal storage subpackge.
//
#ifndef _cNORMAL_STORAGE_H_
#define _cNORMAL_STORAGE_H_
#include "storage/cnarray.h"
#include "storage/cnstack.h"
#endif // _cNORMAL_STORAGE_H_
为了测试这些类,我在main.cpp中创建了一个main函数。// main.cpp
// *****************************************************************
// The main-file.
//
#include <iostream>
#include "cnormal_storage.h"
using namespace std;
int main() {
cnArry<int> arr(10);
arr[9] = 999;
arr[0] = 0;
cout << arr[9] << endl;
cout << arr.getLength();
}
但是编译器(gcc)给我undefined reference to ...
关于cnArray
的错误。
cnarray.cpp
包含cnarray.h
(因为它是实现文件),所以使用#include "storage/cnarray.cpp"
可以正常工作。
编译器似乎找不到cnarray.cpp
中cnarray.h
的实现。
我猜是文件夹结构的问题,你能告诉我怎么解决这个问题吗?
即使将srcstorage
添加到include指令中,也不能修复它。(我也不想把它添加到包含路径中,因为这对包来说非常不方便。)
您可以发布您使用的编译命令吗?
似乎你只编译main.cpp,而不是编译(从而链接)其他.cpp
文件。
我现在可以发现错误了,cnArray.h
声明了一个模板类,而模板类不能在声明的文件之外的另一个文件中实现,因为编译器在编译时必须知道实现,而不是在链接时。
我在互联网上找到了一个解决方案来#include
在头文件中实现,但从编译中排除实现文件。
欢呼