企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
# 第2章-项目目录构建 ​ 首先在一切开始之前,我们应该将最基本的项目架构创建出来。 1)创建Lars代码总目录 ```bash $cd ~/ $mkdir Lars ``` 2) 创建一个模块Lars_reactor lars_reactor是一个网络IO库,是我们要实现的,我们就先以它作为第一个子项目进行构建。 ```bash $mkdir lars_reactor ``` 然后在lars_reactor模块下创建一系列文件,如下 ```bash . ├── example │   └── testlib │   ├── hello_lars.cpp │   └── Makefile ├── include │   └── tcp_server.h ├── lib ├── Makefile └── src └── tcp_server.cpp ``` 3)代码编写 > src/tcp_server.c ```c #include <iostream> void lars_hello() { std::cout <<"lars hello" <<std::endl; } ``` > src/tcp_server.h ```c #pragma once void lars_hello(); ``` ​ 我们要生成一个lib库文件liblreactor.a,来提供一些reactor模块的API接口。 生成liblreactor.a的Makefile如下 > lars_reactor/Makefile ```makefile TARGET=lib/liblreactor.a CXX=g++ CFLAGS=-g -O2 -Wall -fPIC -Wno-deprecated SRC=./src INC=-I./include OBJS = $(addsuffix .o, $(basename $(wildcard $(SRC)/*.cpp))) $(TARGET): $(OBJS) mkdir -p lib ar cqs $@ $^ %.o: %.cpp $(CXX) $(CFLAGS) -c -o $@ $< $(INC) .PHONY: clean clean: -rm -f src/*.o $(TARGET) ``` 4)编译 ```bash $cd lars/lars_reactor/ $make $g++ -g -O2 -Wall -fPIC -Wno-deprecated -c -o src/tcp_server.o src/tcp_server.cpp -I./include mkdir -p lib ar cqs lib/liblreactor.a src/tcp_server.o ``` 我们会在lib下得到一个liblreactor.a库文件。 5)调用liblreactor.a接口 ```bash $cd lars/lars_reactor/ $mkdir example/testlib -p $cd example/testlib/ ``` > hello_lars.cpp ```c #include "tcp_server.h" int main() { lars_hello(); return 0; } ``` > Makefile ```makefile CXX=g++ CFLAGS=-g -O2 -Wall -fPIC -Wno-deprecated INC=-I../../include LIB=-L../../lib -llreactor OBJS = $(addsuffix .o, $(basename $(wildcard *.cc))) all: $(CXX) -o hello_lars $(CFLAGS) hello_lars.cpp $(INC) $(LIB) clean: -rm -f *.o hello_lars ``` 编译 ```bash $ make g++ -o hello_lars -g -O2 -Wall -fPIC -Wno-deprecated hello_lars.cpp -I../../include -L../../lib -llreactor ``` 执行 ```c $ ./hello_lars lars hello ``` 我们现在一个基本的项目目录就构建好了,大致如下 ```bash Lars/ ├── lars_reactor │   ├── example │   │   └── testlib │   │   ├── hello_lars │   │   ├── hello_lars.cpp │   │   └── Makefile │   ├── include │   │   └── tcp_server.h │   ├── lib │   │   └── liblreactor.a │   ├── Makefile │   └── src │   ├── tcp_server.cpp │   └── tcp_server.o └── README.md ``` --- ### 关于作者: 作者:`Aceld(刘丹冰)` mail: [danbing.at@gmail.com](mailto:danbing.at@gmail.com) github: [https://github.com/aceld](https://github.com/aceld) 原创书籍: [https://www.kancloud.cn/@aceld](https://www.kancloud.cn/@aceld) ![](https://img.kancloud.cn/b0/d1/b0d11a21ba62e96aef1c11d5bfff2cf8_227x227.jpg)