#ifndef 用途
- 在 .h 檔確保只會被編譯一次
#ifndef HELLO_H // 有些人會定義成 _HELLO_H_
#define HELLO_H // 但目的就是不會被重複編譯
#include <stdlib.h>
int helloIntro(char** str);
int main() __attribute__((weak));
#endif
#ifndef HELLO_H // 有些人會定義成 _HELLO_H_
#define HELLO_H // 但目的就是不會被重複編譯
#include <stdlib.h>
int helloIntro(char** str);
int main() __attribute__((weak));
#endif
#ifdef DEBUG
int main ()
{
return 0;
}
#endif
gcc -DEBUG other.c -o other.x
int main() __attribute__((weak));
int main ()
{
return 0;
}
int main()
{
char str[5];
sprintf(str, "ABC");
printf("%s\n", str); // output : ABC
return 0;
}
int main()
{
char str[5];
sprintf(str, "ABCDEF");
printf("%s\n", str); // output : ABCDEF
return 0;
}
int main()
{
int ret;
char str[5];
ret = snprintf(str, 5, "ABC");
printf("%s\n", str); // output : ABC
printf("%d\n", ret); // output : 3
return 0;
}/code>
int main()
{
int ret;
char str[5];
ret = snprintf(str, 5, "ABCDEF");
printf("%s\n", str); // output : ABCD
printf("%d\n", ret); // output : 6
return 0;
}
#include<stdio.h>
#include<stdlib.h>
#include<syslog.h>
syslog(LOG_INFO, "hello %s", "woring");
syslog(LOG_ERR, "hello %s", "test");
底下為參數 int priority| LOG_USER | : A miscellaneous user process |
| LOG_MAIL | |
| LOG_DAEMON | : A miscellaneous system daemon |
| LOG_AUTH | : Security (authorization) |
| LOG_SYSLOG | : Syslog |
| LOG_LPR | : Central printer |
| LOG_NEWS | : Network news (e.g. Usenet) |
| LOG_UUCP | : UUCP |
| LOG_CRON | : Cron and At |
| LOG_AUTHPRIV | : Private security (authorization) |
| LOG_FTP | : Ftp server |
| LOG_LOCAL(0~7) | : Locally defined |
enum direction
{
North, // 0
South, // 1
East, // 2
West // 3
};
typedef enum direction Direction;
enum direction
{
North,
South,
East,
West
};
int main(void)
{
Direction dest = East;
return 0;
}
#define Max 10
#define MAX(a,b) ((a) > (b) ? (a) : (b))
#define MINUS(a,b) a - b // 注意這個 a-b 沒加括號很容易出錯
#define MINUS(a,b) (a - b) // Good.
#define MACRO(arg1, arg2) \
do \
{ \
test1; \
test2; \
} while (0)
extern int func(void);
int __attribute__((weak)) func(void)
{
return 0;
}
void real_func()
{
printf("strong func\n");
}
weak.so void real_func() __attribute__((weak))
{
printf("weak func\n");
}
main.c extern void real_func();
void main()
{
real_func();
}
結果 :
// 動態連結無效,只看順序
gcc main.c -lstrong -lweak // 輸出 : strong func
gcc main.c -lweak -lstrong // 輸出 : weak func
// 正常 .o 檔
gcc main.c weak.o strong.o // 輸出 : strong func
gcc main.c strong.o weak.o // 輸出 : strong func