gRPC Visual Studio 2022 + Vcpkg+ Windows编译

gRPC C++ :Visual Studio 2022 + Vcpkg+ Windows配库、编译、调试运行

Time:2023/12/15

Author:Liaojunjian

必需:

1. git
2. cmake
3. VS2022
4. 科学上网工具
5. 强大的在遇到几百个链接错误不崩溃的心态

下载gRPC相关C++源码和实例,这个不可能跑起来,大概率缺失库。

在这里插入图片描述

在这里插入图片描述

安装vcpkg

首先任意位置
打开cmd ,右击git bash here
git clone https://github.com/microsoft/vcpkg.git

vcpkg安装目录 输入.\vcpkg\bootstrap-vcpkg.bat

在vcpkg的根目录下打开cmd,输入
vcpkg install grpc:x64-windows

以及

vcpkg install protobuf protobuf:x64-windows
帮助自动安装grpc和protobuf.

新建两个项目,一个客户端,一个服务端

编写proto文件

例如:

syntax = "proto3";
package HelloWorld;
service Greeter{
     rpc SayHello (HelloRequest)  returns (HelloReply){
}
}

message HelloRequest {

    string name = 1;
}

message HelloReply{
  
   string message =1;

}
任意位置进入cmd用命令行生成
protoc --proto_path=. --cpp_out=. helloWorld.proto

protoc --proto_path=. --grpc_out=. --plugin=protoc-gen-grpc="D:\vcpkg\packages\grpc_x64-windows\tools\grpc\grpc_cpp_plugin.exe" helloWorld.proto    

在这里插入图片描述

得到四个文件

在这里插入图片描述

在这里插入图片描述

VS2022中分别创建一个客户端一个服务端项目,设置项目结构如下。

在这里插入图片描述

在这里插入图片描述

再右击项目–>属性–>C/C++ -->附加包含目录,输入:
D:\vcpkg\installed\x64-windows\include\google\protobuf;D:\vcpkg\installed\x64-windows\include
    
    
//或者相对引用路径
$(SolutionDir)gRPCHelloWorld\AllINCLUDE\include    //包含protobuf和grpc库
再右击项目–>属性–>链接器–>附加库目录,输入:
D:\vcpkg\installed\x64-windows\lib;%(AdditionalLibraryDirectories)
    
//或者相对引用路径
$(SolutionDir)gRPCHelloWorld\AllLIBS\lib    
最后到链接器中的输入静态库(关键):
abseil_dll.lib
absl_flags.lib
absl_flags_commandlineflag.lib
absl_flags_commandlineflag_internal.lib
absl_flags_config.lib
absl_flags_internal.lib
absl_flags_marshalling.lib
absl_flags_parse.lib
absl_flags_private_handle_accessor.lib
absl_flags_program_name.lib
absl_flags_reflection.lib
absl_flags_usage.lib
absl_flags_usage_internal.lib
absl_log_flags.lib
absl_string_view.lib
address_sorting.lib
cares.lib
descriptor_upb_proto.lib
gpr.lib
grpc.lib
grpc_plugin_support.lib
grpc_unsecure.lib
grpc++.lib
grpc++_alts.lib
grpc++_error_details.lib
grpc++_reflection.lib
grpc++_unsecure.lib
grpcpp_channelz.lib
libcrypto.lib
libprotobuf.lib
libprotobuf-lite.lib
libprotoc.lib
libssl.lib
re2.lib
upb.lib
upb_collections.lib
upb_extension_registry.lib
upb_fastdecode.lib
upb_json.lib
upb_mini_table.lib
upb_reflection.lib
upb_textformat.lib
upb_utf8_range.lib
zlib.lib

注意引入以下dll

在这里插入图片描述

到examples文件夹里拷贝 gRPC 测试用例

gRPCHelloWorld.cpp
// gRPCHelloWorld.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <condition_variable>
#include <iostream>
#include <memory>
#include <mutex>
#include <string>

#include "absl/flags/flag.h"
#include "absl/flags/parse.h"

#include <grpcpp/grpcpp.h>

#ifdef BAZEL_BUILD
#include "examples/protos/helloworld.grpc.pb.h"
#else
#include "helloworld.grpc.pb.h"
#endif

ABSL_FLAG(std::string, target, "localhost:50051", "Server address");

using grpc::Channel;
using grpc::ClientContext;
using grpc::Status;
using helloworld::Greeter;
using helloworld::HelloReply;
using helloworld::HelloRequest;

class GreeterClient {
public:
    GreeterClient(std::shared_ptr<Channel> channel)
        : stub_(Greeter::NewStub(channel)) {}

    // Assembles the client's payload, sends it and presents the response back
    // from the server.
    std::string SayHello(const std::string& user) {
        // Data we are sending to the server.
        HelloRequest request;
        request.set_name(user);

        // Container for the data we expect from the server.
        HelloReply reply;

        // Context for the client. It could be used to convey extra information to
        // the server and/or tweak certain RPC behaviors.
        ClientContext context;

        // The actual RPC.
        std::mutex mu;
        std::condition_variable cv;
        bool done = false;
        Status status;
        stub_->async()->SayHello(&context, &request, &reply,
            [&mu, &cv, &done, &status](Status s) {
                status = std::move(s);
                std::lock_guard<std::mutex> lock(mu);
                done = true;
                cv.notify_one();
            });

        std::unique_lock<std::mutex> lock(mu);
        while (!done) {
            cv.wait(lock);
        }

        // Act upon its status.
        if (status.ok()) {
            return reply.message();
        }
        else {
            std::cout << status.error_code() << ": " << status.error_message()
                << std::endl;
            return "RPC failed";
        }
    }

private:
    std::unique_ptr<Greeter::Stub> stub_;
};

int main(int argc, char** argv) {
    absl::ParseCommandLine(argc, argv);
    // Instantiate the client. It requires a channel, out of which the actual RPCs
    // are created. This channel models a connection to an endpoint specified by
    // the argument "--target=" which is the only expected argument.
    std::string target_str = absl::GetFlag(FLAGS_target);
    // We indicate that the channel isn't authenticated (use of
    // InsecureChannelCredentials()).
    GreeterClient greeter(
        grpc::CreateChannel(target_str, grpc::InsecureChannelCredentials()));
    std::string user("world");
    std::string reply = greeter.SayHello(user);
    std::cout << "Greeter received: " << reply << std::endl;

    return 0;
}



gRPCHelloWorldServer.cpp
// gRPCHelloWorldServer.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <iostream>
#include <memory>
#include <string>

#include "absl/flags/flag.h"
#include "absl/flags/parse.h"
#include "absl/strings/str_format.h"

#include <grpcpp/ext/proto_server_reflection_plugin.h>
#include <grpcpp/grpcpp.h>
#include <grpcpp/health_check_service_interface.h>

#ifdef BAZEL_BUILD
#include "examples/protos/helloworld.grpc.pb.h"
#else
#include "helloworld.grpc.pb.h"
#endif

ABSL_FLAG(uint16_t, port, 50051, "Server port for the service");
#if 1
/*using*/
using grpc::CallbackServerContext;
using grpc::Server;
using grpc::ServerBuilder;
using grpc::ServerUnaryReactor;
using grpc::Status;
using helloworld::Greeter;
using helloworld::HelloReply;
using helloworld::HelloRequest;
#endif
// Logic and data behind the server's behavior.
class GreeterServiceImpl final : public Greeter::CallbackService {
    ServerUnaryReactor* SayHello(CallbackServerContext* context,
        const HelloRequest* request,
        HelloReply* reply) override {
        std::string prefix("Hello ");
        reply->set_message(prefix + request->name());

        ServerUnaryReactor* reactor = context->DefaultReactor();
        reactor->Finish(Status::OK);
        return reactor;
    }
};

static void RunServer(uint16_t port) {
    std::string server_address = absl::StrFormat("0.0.0.0:%d", port);
    GreeterServiceImpl service;

    grpc::EnableDefaultHealthCheckService(true);
    grpc::reflection::InitProtoReflectionServerBuilderPlugin();
    ServerBuilder builder;
    // Listen on the given address without any authentication mechanism.
    builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
    // Register "service" as the instance through which we'll communicate with
    // clients. In this case it corresponds to an *synchronous* service.
    builder.RegisterService(&service);
    // Finally assemble the server.
    std::unique_ptr<Server> server(builder.BuildAndStart());
    std::cout << "Server listening on " << server_address << std::endl;

    // Wait for the server to shutdown. Note that some other thread must be
    // responsible for shutting down the server for this call to ever return.
    server->Wait();
}

int main(int argc, char** argv) {
    absl::ParseCommandLine(argc, argv);
    RunServer(absl::GetFlag(FLAGS_port));
    return 0;
}



同时启动项目,结果如下。

在这里插入图片描述

注意运行的时候根据库选择发布类型,推荐Release.

苦尽甘来,从vcpkg安装gRPC到VS2022 中完全从0配置各种文件、各种库,用l各种方法 ,
cmake,或者直接到github下载GRPC源码都没成功。只有vcpkg这个强大的包管理工具,最终gRPC编译成功。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值