1、C和C++代码混合编译
代码的.h
头文件里添加
#ifdef __cplusplus
extern "C" {
#endif
// 中间位置添加头文件的内容
#ifdef __cplusplus
}
#endif
2、结构体初始化 #### 宏定义
#include <stdio.h>
#define STU_ASSIGNMENT(id, name, sex) {(id), (name), (sex)}
typedef struct _Stu{
int id;
char name[16];
char sex[8];
}Stu;
int main(void) {
Stu stu = STU_ASSIGNMENT(20230401, "wangyi", "woman");
printf("Stu id = %d, name = %s, sex = %s\n", stu.id, stu.name, stu.sex);
return 0;
}
3、如何区分定义和声明
定义:给对象分配内存,创建对象
声明:它所描述的并不是本身,而是描述在其它文件中创建的对象。
int num; //定义
extern int num; //声明
4、宏比较大小并返回较大的值
#define MAX(a, b) ((a) <= (b) ? (b) : (a)) // 使用宏记得把参数用括号括起来
5、结构体内置函数指针(本文第2条<结构体初始化 #### 宏定义>拓展,增加函数指针 打印 结构体数据)
#include <stdio.h>
#define STU_ASSIGNMENT(id, name, sex) {(showStu), (id), (name), (sex)}
typedef struct _Stu{
void (*showStu)(struct _Stu *pStu);
int id;
char name[16];
char sex[8];
}Stu;
void showStu(struct _Stu *pStu){
printf("pStu -> [id: %d, name: %s, sex: %s]\n", pStu->id, pStu->name, pStu->sex);
}
int main(void) {
Stu stu = STU_ASSIGNMENT(20230401, "wangyi", "woman");
stu.showStu(&stu);
return 0;
}
6、系统时间戳,单位:us
#include <stdio.h>
#include <time.h>
#include <sys/time.h>
long long getTimeStamp(void) {
long long timeStamp = 0;
struct timeval curTime;
gettimeofday(&curTime, NULL);
timeStamp = ((long long)curTime.tv_sec*1000000 + curTime.tv_usec);
return timeStamp;
}
int main(void) {
long long curTimeStamp = getTimeStamp();
printf("getTimeStamp = %lld us\n", curTimeStamp);
return 0;
}
7、C标准中一些预定义的宏,常用于debug打印输出
__FILE__ :当前源代码文件名
__func__ :当前所在函数名
__LINE__ :当前源代码的行号
__DATE__ :日期 "Mmm dd yyyy"
__TIME__ :源文件编译时间 "hh:mm:ss"
eg:
#include <stdio.h>
int main(void) {
printf("file = %s, func = %s, line = %d, date = %s, computeTime = %s\n", __FILE__, __func__, __LINE__, __DATE__, __TIME__);
return 0;
}
8、一个C++代码 操纵字符和字符串
https://people.sc.fsu.edu/~jburkardt/cpp_src/chrpak/chrpak.cpp
9、C语言实现16进制转字符串
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *hex_to_string(char *hex) {
size_t len = strlen(hex);
// 检查十六进制字符数是否为偶数
if (len % 2 != 0) {
fprintf(stderr, "Invalid hex string! Must have an even number of characters.\\\\n");
return NULL;
}
// 计算输出字符串所需的长度
size_t str_len = len / 2;
char *str = malloc(str_len + 1);
if (!str) {
fprintf(stderr, "Memory allocation failed.\\\\n");
return NULL;
}
// 将十六进制字符串转换为字符并存储到输出字符串中
for (size_t i = 0; i < str_len; i++) {
char hex_byte[3] = {hex[i * 2], hex[i * 2 + 1], '\\0'};
char *endptr;
long byte = strtol(hex_byte, &endptr, 16);
if (*endptr != '\\0') {
fprintf(stderr, "Invalid hex string!\\\\n");
free(str);
return NULL;
}
str[i] = (char) byte;
}
str[str_len] = '\\0';
return str;
}
int main() {
char *hex = "48656c6c6f20576f726c64"; // "Hello World" 的十六进制表示
char *str = hex_to_string(hex);
if (str) {
printf("%s\\\\n", str);
free(str);
} else {
fprintf(stderr, "Conversion failed.\\\\n");
}
return 0;
}