Yifei Kong

Nov 12, 2017

C++ 字面量

C++中的字典字面量

You can actually do this:

std::map<std::string, int> mymap = {{"one", 1}, {"two", 2}, {"three", 3}};

What is actually happening here is that std::map stores an std::pair of the key value types, in this case std::pair. This is only possible because of c++11's …

Jul 27, 2017

make 和 premake

Rule

target: dependencies(sepreated by spaces)
    command(s) to run to build the target from dependencies

Basic usage

in most projects, we have a .h file for functiont interfaces, and the whole program depends on it. typically, all .o files are compiled from corresponding .c source files

cc = gcc              # marco …

Jul 27, 2017

C的编译、调试与静态检查

使用Clang/gcc 常用的选项

-std=c11     设定标准为 c11
-Wall   显示所有警告
-O2 二级优化, 通常够用了
-march=native   释放本地CPU所有指令
-g  如果需要使用 gdb 调试的话

-Dmarco=value    定义宏
-Umarco undef 宏
-Ipath   添加到 include
-llibrary   链接到 liblibbrary.a 文件
-Lpath   添加到链接 

-c  只编译而不链接
-S  生成汇编代码, 但是不生成机器代码
-E   只预处理

-fopenmp     打开 OpenMP 支持
-pthread     添加 pthread 支持 …

May 30, 2017

May 30, 2017

基础 socket 编程

创建与使用 socket, 一个 echo server 和 client

socket 客户端的四个步骤:

  1. 使用 socket 函数创建连接
  2. 使用 connect 连接到服务器
  3. 使用 send 和 recv 接收和发送消息
  4. 使用 close 关闭连接

第一步 创建一个 TCP socket int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); 返回的 sock 可以看做一个 handle, 本质上是一个文件描述符( file descriptor) , 小于0表示错误

表示 socket 地址的结构 sockaddr_in, 其中 in 表示 internet, 不是input …

May 29, 2017

C/C++ 中的 RAII

RAII 的好处

  • 异常安全
  • 保证匹配
  • 防止内存泄露

RAII in C

This is inherent implementation dependent, since the Standard doesn't include such a possibility. For GCC, the cleanup attribute runs a function when a variable goes out of scope:

#include <stdio.h>
void scoped(int * pvariable) {
    printf("variable (%d) goes out of scope …

May 29, 2017

C语言中的 vargs

int max(int n, ...) {
    va_list arg_pointer;
    int result = INT_MIN;

    va_start(arg_pointer, n);
    for (int i = 0; i < n; i++) {
        int arg = va_arg(arg_pointer, int);
        if (arg > result)
            result = arg;
    }
    va_end(arg_pointer);

    return result;
}     

Reference

  1. http://www.cnblogs.com/chinazhangjie/archive/2012/08/18/2645475.html

  2. http://wiki.jikexueyuan.com/project …

May 29, 2017

C语言中的 setjmp/longjmp

首先吐槽一下这个缩写, 好好地 jump 单词才四个字母不用, 非要缩写成 jmp 三个字母, 每次都打错, 蛋疼

在 C 中,goto 语句是不能跨越函数的,而执行这类跳转功能的是 setjmplongjmp 宏。这两个宏对于处理发生在深层嵌套函数调用中的出错情况是非常有用的。

此即为:非局部跳转。非局部指的是,这不是由普通 C 语言 goto 语句在一个函数内实施的跳转,而是在栈上跳过若干调用帧,返回到当前函数调用路径的某个函数中。

#include &lt;setjmp.h&gt;
int  setjmp (jmp_buf env) ;  /*设置调转点*/
void longjmp (jmp_buf env,  int val) ;  /*跳转*/

setjmp 参数 env …

May 29, 2017