Linux系统下C/C++编程

参考视频

Linux下C/CPP开发基础

gcc库使用

root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# vim main.cpp
root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# cat main.cpp 
#include
#include"mymath.h"
using namespace std;

int main(){
	int a=10;
	int b=20;
	int c=add(a, b);
	cout<<a<<"+"<<b<<"="<<c<<endl;
	return 0;
}
 
root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# cat mymath.cpp 
#include"mymath.h"
int add(int a, int b)
{
	return a+b;
}
root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# cat mymath.h
int add(int a, int b);
root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# g++ main.cpp mymath.cpp -o main
root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# ./main 
10+20=30

静态链接库 .a

root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# g++ -c mymath.cpp -o mymath.o
root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# ll mymath.o
-rw-r--r-- 1 root root 1240 Mar 26 19:33 mymath.o
root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# ar rcs libmymath.a mymath.o
root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# g++ -c main.cpp -o main.o  # 编译
root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# g++ main.o -L . -l mymath -o main # 链接
root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# ./main 
10+20=30

动态链接库 .so

root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# g++ mymath.cpp -shared -o libmymath.so
root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# g++ main.o -L . -l mymath -o main
root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# ./main 
./main: error while loading shared libraries: libmymath.so: cannot open shared object file: No such file or directory
root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# cat /etc/ld.so.conf
include /etc/ld.so.conf.d/*.conf

root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# echo "$(pwd)" >> .so: cannot open shared object file: No such file or directory
root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# cat 
-bash: root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp#: No such file or directory
root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# echo "$(pwd)" >> /etc/ld.so.conf
root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# cat /etc/ld.so.conf
include /etc/ld.so.conf.d/*.conf

/root/cpp
root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# ldconfig
root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# ./main 
10+20=30

jsoncpp

jsoncpp usage

#下载 jsoncpp 源码
git clone https://github.com/open-source-parsers/jsoncpp.git 
#进到目录
cd jsoncpp-master
#创建目录
mkdir -p build/release
#进到编译目录
cd build/release
#使用 cmake 进行编译
cmake -DCMAKE_BUILD_TYPE=release -DBUILD_STATIC_LIBS=ON \
-DBUILD_SHARED_LIBS=OFF -DCMAKE_INSTALL_INCLUDEDIR=include/jsoncpp \
-DARCHIVE_INSTALL_DIR=. -G "Unix Makefiles" ../..
#编译和安装
make && make install

examples

root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# vim jsoncpp_demo01.c
root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# cat jsoncpp_demo01.c
#include 
#include 
#include 
 
int main()
{
    std::cout << "Hello World!" << std::endl;
 
    Json::Value root;
    Json::FastWriter fast;
 
    root["ModuleType"] = Json::Value(1);
    root["ModuleCode"] = Json::Value("China");
 
    std::cout<<fast.write(root)<<std::endl;
 
    Json::Value sub;
    sub["version"] = Json::Value("1.0");
    sub["city"] = Json::Value(root);
    fast.write(sub);
 
    std::cout<<sub.toStyledString()<<std::endl;
 
    return 0;
}
root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# g++ jsoncpp_demo01.c -o demo01 -ljsoncpp -std=c++11
root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# ./demo01 
Hello World!
{"ModuleCode":"China","ModuleType":1}

{
	"city" : 
	{
		"ModuleCode" : "China",
		"ModuleType" : 1
	},
	"version" : "1.0"
}

root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# vim jsoncpp_demo02.c
root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# cat jsoncpp_demo02.c 
#include 
#include 
#include 
 
using namespace std;
 
void readJson() {
	std::string strValue = "{\"name\":\"json\",\"array\":[{\"cpp\":\"jsoncpp\"},{\"java\":\"jsoninjava\"},{\"php\":\"support\"}]}";
 
	Json::Reader reader;
	Json::Value value;
 
	if (reader.parse(strValue, value))
	{
		std::string out = value["name"].asString();
		std::cout << out << std::endl;
		const Json::Value arrayObj = value["array"];
		for (unsigned int i = 0; i < arrayObj.size(); i++)
		{
			if (!arrayObj[i].isMember("cpp")) 
				continue;
			out = arrayObj[i]["cpp"].asString();
			std::cout << out;
			if (i != (arrayObj.size() - 1))
				std::cout << std::endl;
		}
	}
}
 
void writeJson() {
 
	Json::Value root;
	Json::Value arrayObj;
	Json::Value item;
 
	item["cpp"] = "jsoncpp";
	item["java"] = "jsoninjava";
	item["php"] = "support";
	arrayObj.append(item);
 
	root["name"] = "json";
	root["array"] = arrayObj;
 
	root.toStyledString();
	std::string out = root.toStyledString();
	std::cout << out << std::endl;
}
 
int main(int argc, char** argv) {
	readJson();
	writeJson();
	return 0;
}
root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# g++ jsoncpp_demo02.c -o demo02 -ljsoncpp -std=c++11
root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# ./demo02 
json
jsoncpp
{
	"array" : 
	[
		{
			"cpp" : "jsoncpp",
			"java" : "jsoninjava",
			"php" : "support"
		}
	],
	"name" : "json"
}

root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# vim jsoncpp_speed.cpp
root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# cat jsoncpp_speed.cpp
/*
 * @Descripttion: 测试jsoncpp的使用方法和性能
 * @version: 1.0
 * @Author: Milo
 * @Date: 2020-06-05 15:14:40
 * @LastEditors: Milo
 * @LastEditTime: 2020-06-05 15:14:40
 */
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include "jsoncpp/json/json.h"
#include "jsoncpp/json/value.h"
#include "jsoncpp/json/reader.h"
#include "jsoncpp/json/writer.h"
 
/*
 
{
  "name": "milo",
  "age": 80,
  "languages": ["C++", "C"],
  "phone": {
    "number": "186****3143",
    "type": "home"
  },
  "books":[
      {
          "name": "Linux kernel development",
          "price":7.7
      },
      {
          "name": "Linux server development",
          "price": 8.0
      }
  ]"vip":true,
  "address": null
}
 */
static uint64_t getNowTime()
{
    struct timeval tval;
    uint64_t nowTime;
 
    gettimeofday(&tval, NULL);
 
    nowTime = tval.tv_sec * 1000L + tval.tv_usec / 1000L;
    return nowTime;
}
 
std::string JsoncppEncodeNew()
{
    std::string jsonStr;
    // 一个value是可以包含多个键值对
    Json::Value root, languages, phone, book, books;
 
    // 姓名
    root["name"] = "milo";
    // 年龄
    root["age"] = 80;
 
    // 语言
    languages[0] = "C++";
    languages[1] = "Java";
    root["languages"] = languages;
 
    // 电话
    phone["number"] = "186****3143";
    phone["type"] = "home";
    root["phone"] = phone;
 
    // 书籍
    book["name"] = "Linux kernel development";
    book["price"] = 7.7;
    books[0] = book;    // 深拷贝
    book["name"] = "Linux server development";
    book["price"] = 8.0;
    books[1] = book;    // 深拷贝
    root["books"] = books;
 
    // 是否为vip
    root["vip"] = true;
 
    // address信息空null
    root["address"] = "yageguoji";
 
    Json::StreamWriterBuilder writerBuilder;
    std::ostringstream os;
    std::unique_ptr<Json::StreamWriter> jsonWriter(writerBuilder.newStreamWriter());
    jsonWriter->write(root, &os);
    jsonStr = os.str();
 
    // std::cout << "Json:\n" << jsonStr << std::endl;
    return jsonStr;
}
 
std::string JsoncppEncodeOld()
{
    std::string jsonStr;
    Json::Value root, languages, phone, book, books;
 
    // 姓名
     root["name"] = "milo";
    //root["name"] = Json::nullValue;
    // 年龄
    root["age"] =  80; 
 
    // 语言
    languages[0] = "C++";
    languages[1] = "Java";
    root["languages"] = languages;
 
    // 电话
    phone["number"] = "186****3143";
    phone["type"] = "home";
    root["phone"] = phone;
 
    // 书籍
    book["name"] = "Linux kernel development";
    book["price"] = (float)7.7;
    books[0] = book;
    book["name"] = "Linux server development";
    book["price"] = (float)8.0;
    books[1] = book;
    root["books"] = books;
 
    // 是否为vip
    root["vip"] = true;
 
    // address信息空null
    root["address"] = "yageguoji"; //;// Json::nullValue; // 如果是null,则要用自定义的Json::nullValue,不能用NULL
 
    Json::FastWriter writer;
    jsonStr = writer.write(root);
 
    // std::cout << "Json:\n" << jsonStr << std::endl;
    return jsonStr;
}
 
// 不能返回引用
Json::Value JsoncppEncodeOldGet()
{
    Json::Value root;
    Json::Value languages, phone, book, books;
 
    // 姓名
    root["name"] = "milo";
    //root["name"] = Json::nullValue;
    // 年龄
    root["age"] =  80; 
 
    // 语言
    languages[0] = "C++";
    languages[1] = "Java";
    root["languages"] = languages;
 
    // 电话
    phone["number"] = "186****3143";
    phone["type"] = "home";
    root["phone"] = phone;
 
    // 书籍
    book["name"] = "Linux kernel development";
    book["price"] = (float)7.7;
    books[0] = book;
    book["name"] = "Linux server development";
    book["price"] = (float)8.0;
    books[1] = book;
    root["books"] = books;
 
    // 是否为vip
    root["vip"] = true;
 
    // address信息空null
    root["address"] = Json::nullValue; //"yageguoji";// Json::nullValue; // 如果是null,则要用自定义的Json::nullValue,不能用NULL
 
 
 
    std::cout << "JsoncppEncodeOldGet:\n"  << std::endl;
    return root;
}
 
void printJsoncpp(Json::Value &root)
{
    if(root["name"].isNull())
    {
        std::cout << "name null\n";
    }
    std::cout << "name: " << root["name"].asString() << std::endl;
    std::cout << "age: " << root["age"].asInt() << std::endl;
 
    Json::Value &languages = root["languages"];
    std::cout << "languages: ";
    for (uint32_t i = 0; i < languages.size(); ++i)
    {
        if (i != 0)
        {
            std::cout << ", ";
        }
        std::cout << languages[i].asString();
    }
    std::cout << std::endl;
 
    Json::Value &phone = root["phone"];
    std::cout << "phone number: " << phone["number"].asString() << ", type: " << phone["type"].asString() << std::endl;
 
    Json::Value &books = root["books"];
    for (uint32_t i = 0; i < books.size(); ++i)
    {
        Json::Value &book = books[i];
        std::cout << "book name: " << book["name"].asString() << ", price: " << book["price"].asFloat() << std::endl;
    }
    std::cout << "vip: " << root["vip"].asBool() << std::endl;
 
    if (!root["address"].isNull())
    {
        std::cout << "address: " << root["address"].asString() << std::endl;
    }
    else
    {
        std::cout << "address is null" << std::endl;
    }
}
 
bool JsoncppDecodeNew(const std::string &info)
{
    if (info.empty())
        return false;
 
    bool res;
    JSONCPP_STRING errs;
    Json::Value root;
    Json::CharReaderBuilder readerBuilder;
    std::unique_ptr const jsonReader(readerBuilder.newCharReader());
    res = jsonReader->parse(info.c_str(), info.c_str() + info.length(), &root, &errs);
    if (!res || !errs.empty())
    {
        std::cout << "parseJson err. " << errs << std::endl;
        return false;
    }
    // printJsoncpp(root);
 
    return true;
}
 
bool JsoncppDecodeOld(const std::string &strJson)
{
    if (strJson.empty())
        return false;
 
    bool res;
 
    Json::Value root;
    Json::Reader jsonReader;
 
    res = jsonReader.parse(strJson, root);
    if (!res)
    {
        std::cout << "jsonReader.parse err. " << std::endl;
        return false;
    }
 
    // printJsoncpp(root);
 
    return true;
}
 
const char *strCjson = "{                 \
	\"name\":	\"milo\",         \
	\"age\":	80,                 \
	\"languages\":	[\"C++\", \"C\"],\
	\"phone\":	{                       \
		\"number\":	\"186****3143\",    \
		\"type\":	\"home\"            \
	},                                  \
	\"books\":	[{                         \
			\"name\":	\"Linux kernel development\",   \
			\"price\":	7.700000        \
		}, {                            \
			\"name\":	\"Linux server development\",   \
			\"price\":	8               \
		}],                             \
	\"vip\":	true,                   \
	\"address\":	null                \
}                                      \
";
#define TEST_COUNT 100000
int main()
{
    std::string jsonStrNew;
    std::string jsonStrOld;
 
    jsonStrNew = JsoncppEncodeNew();
    // JsoncppEncodeNew size: 337
    std::cout << "JsoncppEncodeNew size: " << jsonStrNew.size() << std::endl;
    std::cout << "JsoncppEncodeNew string: " << jsonStrNew << std::endl;
    JsoncppDecodeNew(jsonStrNew);
 
    jsonStrOld = JsoncppEncodeOld();
    // JsoncppEncodeOld size: 248
    std::cout << "\n\nJsoncppEncodeOld size: " << jsonStrOld.size() << std::endl;
    std::cout << "JsoncppEncodeOld string: " << jsonStrOld << std::endl;
    JsoncppDecodeOld(jsonStrOld);
 
    Json::Value root = JsoncppEncodeOldGet();
    Json::FastWriter writer;
    std::cout << "writer:\n"  << std::endl;
    std::string jsonStr = writer.write(root);
    std::cout << "\n\njsonStr string: " << jsonStrOld << std::endl;
#if 1
    uint64_t startTime;
    uint64_t nowTime;
    
    startTime = getNowTime();
    std::cout << "jsoncpp encode time testing" << std::endl;
    for(int i = 0; i < TEST_COUNT; i++)
    {
        JsoncppEncodeNew();
    }
    nowTime = getNowTime();
    std::cout << "jsoncpp encode " << TEST_COUNT << " time, need time: "
         << nowTime-startTime << "ms"  << std::endl;
 
    startTime = getNowTime();
    std::cout << "\njsoncpp encode time testing" << std::endl;
    for(int i = 0; i < TEST_COUNT; i++)
    {
        JsoncppEncodeOld();
    }
    nowTime = getNowTime();
    std::cout << "jsoncpp encode " << TEST_COUNT << " time, need time: "
         << nowTime-startTime << "ms"  << std::endl;
 
    startTime = getNowTime();
    std::cout << "\njsoncpp decode time testing" << std::endl;
    for(int i = 0; i < TEST_COUNT; i++)
    {
        JsoncppDecodeNew(jsonStrNew);
    }
    nowTime = getNowTime();
    std::cout << "jsoncpp decode " << TEST_COUNT << " time, need time: "
         << nowTime-startTime << "ms"  << std::endl;
 
    startTime = getNowTime();
    std::cout << "\njsoncpp decode time testing" << std::endl;
    for(int i = 0; i < TEST_COUNT; i++)
    {
        JsoncppDecodeOld(jsonStrNew);
    }
    nowTime = getNowTime();
    std::cout << "jsoncpp decode " << TEST_COUNT << " time, need time: "
         << nowTime-startTime << "ms"  << std::endl;
#endif
 
    return 0;
}
root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# g++ jsoncpp_speed.cpp -o jsoncpp_speed -ljsoncpp -std=c++11
root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# ./jsoncpp_speed
JsoncppEncodeNew size: 345
JsoncppEncodeNew string: {
	"address" : "yageguoji",
	"age" : 80,
	"books" : 
	[
		{
			"name" : "Linux kernel development",
			"price" : 7.7000000000000002
		},
		{
			"name" : "Linux server development",
			"price" : 8.0
		}
	],
	"languages" : 
	[
		"C++",
		"Java"
	],
	"name" : "milo",
	"phone" : 
	{
		"number" : "186****3143",
		"type" : "home"
	},
	"vip" : true
}


JsoncppEncodeOld size: 253
JsoncppEncodeOld string: {"address":"yageguoji","age":80,"books":[{"name":"Linux kernel development","price":7.6999998092651367},{"name":"Linux server development","price":8.0}],"languages":["C++","Java"],"name":"milo","phone":{"number":"186****3143","type":"home"},"vip":true}

JsoncppEncodeOldGet:

writer:



jsonStr string: {"address":"yageguoji","age":80,"books":[{"name":"Linux kernel development","price":7.6999998092651367},{"name":"Linux server development","price":8.0}],"languages":["C++","Java"],"name":"milo","phone":{"number":"186****3143","type":"home"},"vip":true}

jsoncpp encode time testing
jsoncpp encode 100000 time, need time: 1435ms

jsoncpp encode time testing
jsoncpp encode 100000 time, need time: 789ms

jsoncpp decode time testing
jsoncpp decode 100000 time, need time: 988ms

jsoncpp decode time testing
jsoncpp decode 100000 time, need time: 643ms

视频中
main.cpp

#include 
#include 
#include 
#include "json.h"
using namespace std;
int main() {
	ifstream scriptFile;
	string name = "./test.json";
	scriptFile.open(name);
	if (!scriptFile.is_open())
	{
		cout << "File" << name << " does not exist!" << endl;
		return 0;
	}
	Json::CharReaderBuilder builder;
	builder["collectComments"] = true;
	JSONCPP_STRING errs;
	Json::Value root;
	if (!parseFromStream(builder scriptFile, &root, &errs) {
		cout << "Wrong in paser from json file" << endl;
			throw runtime_error("");
	}
	auto str=root.toStyledString();
	cout<<str<<endl;
	return 0;
}

Linux系统下C/C++编程_第1张图片
Linux系统下C/C++编程_第2张图片

makefile

makefile

root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# make
g++ -o main mymath.cpp main.cpp
root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# ./main 
10+20=30
root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# vim makefile 
root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# make clean && make
rm -f main
g++ -o main mymath.cpp main.cpp
root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# ./main 
10+20=30
root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# cat makefile 
cpp=$(wildcard *.cpp)
obj=main
$(obj):$(cpp)
	g++ -o $@ $^
.PHONY: clean
clean:
	rm -f $(obj)

cmake

CMake 良心教程,教你从入门到入魂 - 程序员阿德的文章 - 知乎

# 目录下有CMakeLists.txt
cmake .
# 生成makefile文件
make
# 自动编译

example

CMakeLists.txt

cmake_minimum_required(VERSION 3.5)
  
# set the project name
project(Tutorial LANGUAGES CXX)

set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

# add the executable
add_executable(${PROJECT_NAME} tutorial.cpp)

tutorial.cpp

#include 
#include 
#include 
#include 

int main(int argc, char* argv[])
{
    if (argc < 2) {
        std::cout << "Usage: " << argv[0] << " number" << std::endl;
        return 1;
    }

    // convert input to double
    const double inputValue = atof(argv[1]);

    // calculate square root
    const double outputValue = sqrt(inputValue);
    std::cout << "The square root of " << inputValue
              << " is " << outputValue
              << std::endl;
    return 0;
}

Linux系统下C/C++编程_第3张图片
视频
Linux系统下C/C++编程_第4张图片
cmake 用于 jsoncpp/example

 cd ..
 g++ ./stringWrite/stringWrite.cpp -ljsoncpp -std=c++11 -o stringWrite
 g++ ./stringWrite/stringWrite.cpp -ljsoncpp -std=c++11 -o ./stringWrite/stringWrite.o
 ./stringWrite/stringWrite.o
 g++ ./streamWrite/streamWrite.cpp -ljsoncpp -std=c++11 -o ./streamWrite/streamWrite.o
 vim ./streamWrite/streamWrite.cpp
 cat ./streamWrite/streamWrite.cpp
 g++ ./streamWrite/streamWrite.cpp -ljsoncpp -std=c++11 -o ./streamWrite/streamWrite.o
 ./streamWrite/streamWrite.o
 cat ./readFromString/readFromString.cpp 

Linux系统下C/C++编程_第5张图片

你可能感兴趣的:(linux,linux,c语言,c++)