合理编写C++模块(.h、.cc)

时间:2022-09-24 14:21:41

模块划分

合理编写模块的 demo.h、demo.cc

下例为C++为后端服务编写的探活检测服务

  • health_server.h
#ifndef  HEALTH_SERVER_H      
#define  HEALTH_SERVER_H
#include <iostream>
//#include "utils/flags.h"
void health_server( const std::string &health_host , const std::string &health_port );
#endif
  1. 必加#ifndef: 预处理功能(宏定义,文件包含和条件编译)中的条件编译,主要用来防止重复编译,“multiple define”错误
  2. .h中的其它预处理功能include***,遵循最小使用原则,如上例 仅使用std::string,则对应 仅加入#include<iostream>
  3. .cc文件也需要添加 对应#include "health_server.h" 文件
    health_server.cc
#include <dirent.h>
#include <fstream>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

#include <atomic>
#include <memory>
#include <thread>
#include <iostream>
#include "health_server.h"
#include "./http_server.h"

mg_serve_http_opts oppo::HttpServer::s_server_option;
std::atomic<bool> server_stop(true);
std::unordered_map<std::string, oppo::ReqHandler> oppo::HttpServer::s_handler_map;
std::unordered_set<mg_connection *> oppo::HttpServer::s_websocket_session_set;

static bool HandleHealth(std::string url, std::string body,
  mg_connection *c, oppo::OnRspCallback rsp_callback)
{
  if (!server_stop)
	  rsp_callback(c, "OK");
  else
    rsp_callback(c, "STOP");

	return true;
}

static bool HandleStop(std::string url, std::string body,
  mg_connection *c, oppo::OnRspCallback rsp_callback)
{
  if (!server_stop) {
    server_stop = true;
    rsp_callback(c, "STOP OK");
  }
  else {
    rsp_callback(c, "IS STOP");
  }

	return true;
}

static bool HandleStart(std::string url, std::string body,
  mg_connection *c, oppo::OnRspCallback rsp_callback)
{
  if (server_stop) {
    server_stop = false;
    rsp_callback(c, "START OK");
  }
  else {
    rsp_callback(c, "IS START");
  }

	return true;
}

void health_server( const std::string &health_host , const std::string &health_port ){
      std::string health_address(health_host + ":" + health_port);
      auto health_server = std::unique_ptr<oppo::HttpServer>(new oppo::HttpServer);
      std::thread http_thread([&health_server, health_address]() {
        health_server->Init(health_address);
        health_server->AddHandler("/asr/health", HandleHealth);
        health_server->AddHandler("/asr/stop", HandleStop);
        health_server->AddHandler("/asr/start", HandleStart);
        health_server->Start();
      });
      http_thread.join();
}

依赖库部分:

  • gflags使用DEFINE_int32(port, 10086, "grpc listening port")
#include <memory>
#include <gflags/gflags.h>
DEFINE_int32(port, 10086, "grpc listening port");
  • atomic:原子变量,一般在多线程作为锁使用 依赖:#include <atomic>

ERROR

  • 未定义的引用
  • 命令行编写:g++ speech-service-main.cc http_server.cc mongoose.cc -lpthread,严格按照依赖顺序写,-l链接动态库
  • CMakeList.txt:
  add_library(health_server STATIC
    http/health_server.cc
    http/http_server.cc
    http/mongoose.cc
  )
  target_link_libraries(health_server PUBLIC pthread)

  add_executable(grpc_server_main bin/grpc_server_main.cc)
  target_link_libraries(grpc_server_main PUBLIC health_server)