栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

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

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

编译原理——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;
}

编译成功。 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/702962.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号