java2python 发表于 2020-5-23 21:14:58

多个C文件如何能执行通过

mul_a.cpp
#include<stdio.h>
#include "mul_b.h"

int main()
{
   int hard = add(1,1);
   printf("hard=%d\n",hard);
   return 0;
}
mul_b.cpp
#include<stdio.h>
int add(int a,int b)
{
    return a+b;
}

mul_b.h
int add(int a,int b);


执行mul_a.cpp:
> Executing task: "g++ -O2" -g d:\Tools\Vsd-cpp\test\mul_a.cpp -o d:\Tools\Vsd-cpp\test/mul_a.exe -ggdb3 -Wall -static-libgcc -std=c++17 -Wno-format -fexec-charset=GBK -finput-charset=UTF-8 <

d:/mingw/bin/../lib/gcc/mingw32/9.2.0/../../../../mingw32/bin/ld.exe: C:\Users\ADMINI~1\AppData\Local\Temp\ccTiwuC3.o: in function `main':
d:/Tools/Vsd-cpp/test/mul_a.cpp:6: undefined reference to `add(int, int)'
collect2.exe: error: ld returned 1 exit status
The terminal process terminated with exit code: 1

Terminal will be reused by tasks, press any key to close it.

永恒的蓝色梦想 发表于 2020-5-23 21:18:01

试试改成
mul_a.cpp#include<stdio.h>
#include "mul_b.h"

extern int(*add)(int,int)
int main()
{
   int hard = add(1,1);
   printf("hard=%d\n",hard);
   return 0;
}

java2python 发表于 2020-5-23 21:28:40

永恒的蓝色梦想 发表于 2020-5-23 21:18
试试改成
mul_a.cpp

这样编译可以通过,执行和之前一样:d:/Tools/Vsd-cpp/test/mul_a.cpp:6: undefined reference to `add(int, int)'
#include<stdio.h>
//#include "mul_b.h"

extern int(*add)(int,int);
int main()
{
   int hard = add(1,1);
   printf("hard=%d\n",hard);
   return 0;
}

如果两个同时打开,就会编译阶段报错(一看函数定义成了不同类型,当然同一类型的话,就是重复定义了):'int (* add)(int, int)' redeclared as different kind of entitygcc
#include<stdio.h>
#include "mul_b.h"

extern int(*add)(int,int);
int main()
{
   int hard = add(1,1);
   printf("hard=%d\n",hard);
   return 0;
}
虽然还是通不过,谢谢啦。

永恒的蓝色梦想 发表于 2020-5-23 21:31:49

java2python 发表于 2020-5-23 21:28
这样编译可以通过,执行和之前一样:d:/Tools/Vsd-cpp/test/mul_a.cpp:6: undefined reference to `add(i ...

试试#include<stdio.h>
#include "mul_b.h"

extern int add(int,int);
int main()
{
   int hard = add(1,1);
   printf("hard=%d\n",hard);
   return 0;
}?

CodingCat_k 发表于 2020-5-23 21:36:13

对于多文件编译,首先保证头文件与函数定义文件路径正确;
如果是Windows用户请参考你的IDE如何建立C/C++工程;
Linux用户直接
g++ mul_a.cpp mul_b.cpp -o MUL.out
./MUL.out
即可执行。
=====================================================================
头文件写法建议格式,xx.c一般只写函数、算法等具体实现
#ifndef _MUL
#define _MUL
//写入要用的头文件,结构体,类命等;但是,其中一定不要有实例!!!
#include <stdio.h>
//函数声明
int add(int,int);

#endif

java2python 发表于 2020-5-23 21:41:57

永恒的蓝色梦想 发表于 2020-5-23 21:31
试试?

这样还是不行,其实我试了很多次了,应该只能是像5楼说的,既然是多个文件,要从工程设定,以及头文件的写法来试一试。

java2python 发表于 2020-5-23 21:43:39

CodingCat_k 发表于 2020-5-23 21:36
对于多文件编译,首先保证头文件与函数定义文件路径正确;
如果是Windows用户请参考你的IDE如何建立C/C++ ...

嗯,谢谢,应该就是这个原因了。

java2python 发表于 2020-5-23 21:57:31

直接打开DOS,gcc就行了
D:\Tools\Vsd-cpp\test>gcc -o mul_a.exe mul_b.cpp mul_a.cpp
D:\Tools\Vsd-cpp\test>mul_a
hard=2
大概以上定义是没有问题的,只是用的IDE(vsCode),然后编译,执行都在里面,可能他也就提供一个文件编译执行的缺省配置文件,如果是多个大概需要在设定文件中动手,告诉他怎么你想怎么编译,谢谢大家,启发了思路。
页: [1]
查看完整版本: 多个C文件如何能执行通过