使用extern变量或不使用extern变量之间的区别

时间:2018-06-15 02:37:10

标签: c variables header extern

我对使用" extern"的变量定义和声明有点困惑。关键词。假设我想要一个变量'计时器'可以在多个c文件中使用。然后我可以:

在c1.h

#arg1: the PCA object that we want to plot
#arg2: the list of sample names
#arg3: where to save the plots
#arg4: description of the treatment done

PlotPCA<- function(arg1, arg2, arg3, arg4){

  library(ggplot2)
  DFplot<-data.frame(arg1$x, Sple=arg2)
  arg2<-as.factor(arg2)
  DFplot.PoV <- arg1$sdev^2/sum(arg1$sdev^2)
  LoadMat1 <- arg1$rotation             # the matrix of variable loadings (i.e., a matrix whose columns contain the eigenvectors)
  ScoreMat1 <- predict(arg1)
  percentage<-paste( colnames(DFplot), "(", paste(as.character((round(DFplot.PoV, digits = 4))*100), "%", ")", sep="") )

  themePCA<-theme(panel.background = element_blank(),panel.border=element_rect(fill=NA),panel.grid.major = element_blank(),panel.grid.minor = element_blank(),strip.background=element_blank(),axis.text.x=element_text(colour="black"),axis.text.y=element_text(colour="black"),axis.ticks=element_line(colour="black"),plot.margin=unit(c(1,1,1,1),"line"))


  setwd(arg3)
  png(file=paste0("PC1$2 on ",arg4,Sys.Date(),".png"),width=4000,height=3000,res =300)
  ggplot(DFplot,aes(x=PC1,y=PC2,col=arg2, label=arg2))+
    labs(title=paste0("PC1$2 on",arg4,Sys.Date()),
         colour="Samples (same color =
         same composition)")+
    geom_text()+                     # Add labels
    themePCA+                       #for whit background
    xlab(percentage[1])+ ylab(percentage[2])+
    theme(legend.position="none")
  dev.off()

  setwd(arg3)
  png(file=paste0("PC2$3 on ", arg4, Sys.Date(), ".png"), width=4000,height=3000,res =300,antialias = c("default"))
  ggplot(DFplot,aes(x=PC3,y=PC4,col=arg2, label=arg2))+
    labs(title=paste0("PC2$3 on", arg4, Sys.Date()),
         colour="Samples (same color =
         same composition)")+
    #geom_point(size=0.5,alpha=0.5)+ #Size and alpha just for fun
    geom_text()+                     # Add labels
    #scale_color_manual(values=ColPB)+
    themePCA+                       #for whit background
    xlab(percentage[3])+ ylab(percentage[4])+
    theme(legend.position="none")
  dev.off()
}'

然后在c1.c

int timer;

然后在c2.c

#include "c1.h"
void timer_increase() {
    timer++
}

但是,当我使用extern变量时:

在c1.h

#include "c1.h"
void print_timer() {
    printf("%d", timer);
}

然后在c1.c

extern int timer;

然后在c2.c

#include "c1.h"
int timer;
void timer_increase() {
    timer++
}

两个脚本都运行正常,我看不出任何必须使用extern来声明变量的原因。任何人都可以给我任何提示吗?

1 个答案:

答案 0 :(得分:0)

您必须定义一次变量并在标头中声明它,以便其余文件可以看到该变量。

如果在头文件中不使用extern,则每次在多个文件中定义相同的变量时。