举报

一个项目包含多个源文件,怎么将这几个源文件联系起来?(vs2010)

0

一个项目包含多个源文件,每个源文件实现一个特定的功能。一个源文件中包含主函数,其他源文件中各定义了一个函数,那怎么才能把这些源文件联系起来呢?(vs2010)

ava
王凯

2020-3-27

举报
1

将函数的声明简单的写到 .h 里面,然后需要的 .cpp 引用这个 .h 就好了。

举例:

以下示例包含三个文件:c1.cpp、c2.cpp、d.h。

c1.cpp:

#include "d.h"

int main()
{
	g_num = 3;
	printf("%d\n", mytest());
	return 0;
}

c2.cpp:

#include "d.h"

// 定义全局变量 g_num(也可以定义在 c1.cpp,但只能在一个地方定义)
int g_num;

// 定义函数 mytest
int mytest()
{
	return g_num * 2;
}

d.h:

#pragma once

#include <stdio.h>
extern int g_num; 	// 声明外部变量 g_num
int mytest(); 		// 声明函数 mytest

编译执行,即可看到效果。

ava
慢羊羊

2020-3-27

这个d.h是头文件吗? -  王凯  2020-3-27
举报
@王凯 .h 显然是头文件啊 -  慢羊羊  2020-3-27
举报
技术讨论社区