编译原理——gcc学习中的一次错误

编译原理——gcc学习中的一次错误,第1张

编译原理——gcc学习中的一次错误

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;
}

编译成功。 

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5703068.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存