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
本文作者:乘舟凉
本文链接:https://www.cnblogs.com/czlnb/p/16489982.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步