Lỗi LNK2019 nhưng liên quan đến vị trí khai báo hàm

mình đang thử tạo một static lib theo hướng dẫn của microsoft trên vs 2019 thì lúc build thì dính lỗi LNK2019 nhưng đã mò lỗi, mà thấy rằng nếu mình move hết toàn bộ code của hàm ghi() của class docghiio từ relib.cpp sang relib.h thì hết lỗi, chạy bình thường, còn khia tách ra một header riêng một cpp riêng thì bị lỗi @@.
lỗi : unresolved external symbol “public: void __thiscall relib::quanlyteptin::docghiio::ghi(int &)” (…) referenced in function _main App C:\Users…\App.obj

image

// App.cpp .exe
#include <iostream>
#include "relib.h"
int main() {
    relib::quanlyteptin::docghiio A;
    A.mo("c:/pic/test.txt");
    int a = 0;
    A.ghi(a);
}
//relib.h .lib
#include <iostream>
#include <fstream>

namespace relib {
	namespace quanlyteptin {
		class docghiio {
		private:
			std::fstream tep;
		public:
			void mo(const char* _duongDan);

			template<typename _kieu>
			void ghi(_kieu&);
		};
	}
}
// relib.cpp .lib
#include "relib.h"

namespace relib {
	namespace quanlyteptin {

		void docghiio::mo(const char* _duongDan)
		{
			this->tep.open(_duongDan, std::ios::in | std::ios::out | std::ios::binary | std::ios::app);
			std::cout << "> Mo tep" << (tep.is_open() ? " " : " khong ") << "thanh cong" << std::endl;
		}

		template<typename _kieu>
		void docghiio::ghi(_kieu& _duLieuGhi)
		{
			std::cout << "> " << tep.tellp() << std::endl;
			tep.write((char*)&_duLieuGhi, sizeof(_kieu));
			std::cout << "> " << tep.tellp() << std::endl;
		}
	}
}

Có thêm tham chiếu (reference) cho App sang relib chưa? Hoặc dựng relib thành thư viện (relib.lib) rồi thêm vào App?

2 Likes

mình đã add reference với relib rồi. và cả dir nữa

Hàm ghi của bạn là template thì chỉ có thể đặt trong file header thôi bạn ơi.
Bạn tham khảo thêm ở đây để biết tại sao, và có cả cách work around nữa á

5 Likes
83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?