Q:以下例子能否编译成可执行程序?
test.h:
#ifndef __TEST_H__ #define __TEST_H__ int add(int a, int b) { return a + b; } int test01(int a, int b); #endif
test.c:
#include "test.h" int test01(int a, int b) { return add(a, b); }
main.c:
#include "test.h" int main() { int a = 10; int c; c = add(a, 10); c = test01(c, 20); return c; }
使用gcc指令编译:
gcc -o main main.c test.c
编译失败,信息如下:
总结原因:链接时出错,test和main中出现了两次add函数。
修改办法:
方法1. 在test.c文件中书写add()方法体:
test.h:
#ifndef __TEST_H__ #define __TEST_H__ int add(int a, int b); int test01(int a, int b); #endif
test.c:
#include "test.h" int add(int a, int b) { return a + b; } int test01(int a, int b) { return add(a, b); }
main.c:
#include "test.h" int main() { int a = 10; int c; c = add(a, 10); c = test01(c, 20); return c; }
解决了重复问题,编译成功。
方法2. test.h中声明add函数为静态函数(static):
test.h:
#ifndef __TEST_H__ #define __TEST_H__ static int add(int a, int b) { return a + b; } int test01(int a, int b); #endif
test.c:
#include "test.h" int test01(int a, int b) { return add(a, b); }
main.c:
#include "test.h" int main() { int a = 10; int c; c = add(a, 10); c = test01(c, 20); return c; }
编译成功。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)