c++ 如何在头文件里写实现代码

问题提出

现在有一种hpp文件,它是直接实现代码,其实它就是个头文件,但是在头文件里编写实现代码会重定义错误

test.h

#pragma once
#include <iostream>
void hello() {
	printf("hello");
}

test.cpp

#include "test.h"

main.cpp

#include <stdio.h>
#include "test.h"
int main(int argc, char** argv) {
	
	hello();
	return 0;
}

上面的代码执行结果1>test.obj : error LNK2005: "void __cdecl hello(void)" (?hello@@YAXXZ) 已经在 main.obj 中定义 1>D:\document\learn\window api编程\2-2\Project1\Debug\Project1.exe : fatal error LNK1169: 找到一个或多个多重定义的符号

如何避免重定义呢?

方法一

可以使用内联函数
test.h

#pragma once
#include <iostream>
void inline hello() {
	printf("hello");
}

test.cpp

#include "test.h"

main.cpp

#include <stdio.h>
#include "test.h"
int main(int argc, char** argv) {
	
	hello();
	return 0;
}

但是这中方法只能在函数比较小的情况下使用,不然的话太浪费内存了

方法二

使用类进行封装

test.h

#pragma once
#include <iostream>
class Test {
public:
	static void hello() {
		printf("hello");
	}
};

test.cpp

#include "test.h"

main.cpp

#include <stdio.h>
#include "test.h"
int main(int argc, char** argv) {
	
	Test::hello();
	return 0;
}

使用场景

在头文件里写代码有什么用呢?c++有一个非常不好的点,就是接口使用std会产生很多问题,但是直接使用基本类型又太繁琐,这个时候就可以在头文件对导出函数进一步封装,使接口变的更加友好

#pragma once
#ifndef HEADER_INSTALOADDER
#define HEADER_INSTALOADDER

#include <iostream>

using namespace std;

#ifndef  DLL_EXPORT
#ifdef _WIN32
#define  DLL_EXPORT __declspec(dllexport)
#elif defined __APPLE__
#define  DLL_EXPORT 
#endif 
#endif 

string inline downloadProfile(string username, string savePath);
string inline downloadStory(string username, string savePath);
string inline downloadPost(string url, string savePath);



DLL_EXPORT void downloadProfileInternal(char*& ret, const char* username, const char* savePath);
DLL_EXPORT void downloadStoryInternal(char*& ret, const char* username, const char* savePath);
DLL_EXPORT void downloadPostInternal(char*& ret, const char* url, const char* savePath);
DLL_EXPORT void releaseResult(char* ret);


string inline downloadProfile(string username, string savePath) {

	char* ret = nullptr;
	downloadProfileInternal(ret, username.c_str(), savePath.c_str());
	string rlt(ret);
	releaseResult(ret);
	return rlt;
}
string inline downloadStory(string username, string savePath) {

	char* ret = nullptr;
	downloadStoryInternal(ret, username.c_str(), savePath.c_str());
	string rlt(ret);
	releaseResult(ret);
	return rlt;
}
string inline downloadPost(string url, string savePath) {

	char* ret = nullptr;
	downloadPostInternal(ret, url.c_str(), savePath.c_str());
	string rlt(ret);
	releaseResult(ret);
	return rlt;
}
#endif // HEADER_INSTALOADDER


posted @ 2022-07-18 12:11  乘舟凉  阅读(664)  评论(0编辑  收藏  举报