|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
c 里面有没有像 python 那种 import numpy as np
然后 np.func() 使用对应函数的东西
之所以要这种的,是因为我有一个 main.c, 然后里面 include 了三个.c 文件 (A.c B.c C.c)
然后这三个里面,均 include 另一个 .c 文件 (D.c),共用里面的function
那么问题来了,在 main.c 里面,相当于同时 include 了三遍 D.c,有没有办法解决?
我知道最沙雕的办法就是把 D.c 里面的放进 A B C 里,但是这样依然会重复定义 function 吧?
你不应该 include .c 文件,虽然这不会有语法错误
这么写,语法上确实没问题,也确实有一些程序库使用 include .c 文件的方法完成一些特殊任务
通常是下面这样
- #define name x_name
- #include <name.c>
- #undef name
复制代码
这样会把 name.c 文件中的所有 name 改成 x_name,然后 include 到当前 .c 文件
在另一个 .c 文件中会这样
- #define name y_name
- #include <name.c>
- #undef name
复制代码
另一个
- #define name z_name
- #include <name.c>
- #undef name
复制代码
这样的代码在一些库中确实存在,但是不多见,真的不多,至少我见过的这样的用法真的不多
回到你的问题,不建议 include .c 文件
你可以创建 .h 文件,把其他文件中要调用的函数,在 .h 文件中声明一下,.c 文件中定义
别的地方要使用的时候,就 include .h 文件
像下面这样
main.c
- #include "a.h"
- #include "b.h"
- #include "c.h"
- #include "d.h"
- #include <stdio.h>
- int main(void) {
- printf("ay: %d\n", ay(0));
- printf("az: %s\n", az(1) ? "true" : "false");
- printf("by: %s\n", by(2) ? "true" : "false");
- printf("cz: %d\n", cz(0));
- printf("dc: %c\n", dc(3));
- printf("dd: %lf\n", dd(4));
- return 0;
- }
复制代码
a.h
- #ifndef _A_H_
- #define _A_H_
- #include <stdbool.h>
- int ay(int n);
- bool az(int n);
- #endif
复制代码
a.c
- #include "a.h"
- #include "d.h"
- #include <stdio.h>
- // static 函数留着自己用,不导出,外部不能用
- // 总会有一些函数是不希望外部调用的
- static const char *ax(size_t index) {
- static char *string[] = {
- "0123",
- "abcd",
- "xxxx",
- " "
- };
- return string[index];
- }
- int ay(int n) {
- printf("%d\n", 1 + db(n));
- return -n;
- }
- bool az(int n) {
- printf("%s\n", ax(n));
- return n == dc(n + 1);
- }
复制代码
b.h
- #ifndef _B_H_
- #define _B_H_
- #include <stdbool.h>
- bool by(int n);
- #endif
复制代码
b.c
- #include "b.h"
- #include "d.h"
- #include <stdio.h>
- static int bx(int index) {
- return 100 + index - da();
- }
- static int bx_n(size_t index) {
- return 101 + index + dc(index);
- }
- bool by(int n) {
- printf("%d: %lf\n", bx(1) + bx_n(1), dd(n));
- return n == bx(1);
- }
复制代码
c.h
- #ifndef _C_H_
- #define _C_H_
- int cz(int n);
- #endif
复制代码
c.c
- #include "c.h"
- #include "d.h"
- #include <stddef.h>
- static int cc(int index) {
- return index + dc(index);
- }
- static int cn(size_t index) {
- return index + '0' + da();
- }
- int cz(int n) {
- return cc(n) + cn(n) - db(n);
- }
复制代码
d.h
- #ifndef _D_H_
- #define _D_H_
- int da(void);
- int db(int n);
- char dc(char ch);
- double dd(double x);
- #endif
复制代码
d.c
- #include "d.h"
- int da(void) {
- return 1;
- }
- int db(int n) {
- return ' ' + n;
- }
- char dc(char ch) {
- return ch + '0';
- }
- double dd(double x) {
- return x * x;
- }
复制代码
编译命令
- gcc -g -Wall -o main main.c a.c b.c c.c d.c
复制代码
运行,(输出没有任何意义,^_^)
- $ ./main
- 33
- ay: 0
- abcd
- az: false
- 251: 4.000000
- by: false
- cz: 65
- dc: 3
- dd: 16.000000
- $
复制代码
|
|