我的代码结构如下:
passivetm_formal.c:
#include "CPML_profile.c"
int main(int argc, char* argv[])
{
int n1,n2;
float *p1,*p2;
n1=1;
n2=2;
p1=(float*)calloc(n1,sizeof(float));
p2=(float*)calloc(n2,sizeof(float));
CPML_profile(p1,p2);
...
}
CPML_profile.c:
#include <stdio.h>
#include <math.h>
void CPML_profile(float *p1, float *p2)
{
extern int n1,n2;
...
}
但是当我编译这两个代码时,错误显示:
CPML_profile.o: In function `CPML_profile':
CPML_profile.c:(.text+0x0): multiple definition of `CPML_profile'
passivertm_formal.o:passivertm_formal.c:(.text+0x0): first defined here
passivertm_formal.o: In function `CPML_profile':
passivertm_formal.c:(.text+0x13): undefined reference to `n1'
passivertm_formal.c:(.text+0x1b): undefined reference to `n2'
CPML_profile.o: In function `CPML_profile':
CPML_profile.c:(.text+0x13): undefined reference to `n1'
CPML_profile.c:(.text+0x1b): undefined reference to `n2'
有人能弄清楚为什么会发生这种情况吗?
最佳答案
首先,不要包含 .c
文件,只需创建一个带有函数原型(prototype)的 .h
文件:
#include "CPML_profile.h"
.h 包含:
#pragma once
void CPML_profile(<... function parameters ...>);
现在,n1
和 n2
不是全局变量。它们是来自 main
过程的局部变量(除了这是您的程序入口点之外,它与其他过程没有什么不同),您无法从其他过程或文件访问它们。
将 n1
和 n2
的声明移至全局范围(但我不推荐该解决方案)
int n1,n2;
int main(int argc, char* argv[])
{
在您的情况下,为什么不将它们作为参数传递,因为您已经传递了 float 组:
p1=calloc(n1,sizeof(float));
p2=calloc(n2,sizeof(float)); # BTW: another issue: you're not allocating p2 but p1 twice: ouch!!
CPML_profile(p1,p2,n1,n2);
现在:
void CPML_profile(float *p1, float *p2, int n1, int n2)
{
此解决方案更加干净,并且允许在多线程环境中使用该函数/不需要 n1
和 n2
的全局符号
其他建议:在打开警告的情况下进行编译可能会显示您正在使用未初始化的 p2
。
关于c - 在两个代码中错误地使用了 C 中的 extern,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51063691/