在不同的文件中使用相同的变量(使用extern)

时间:2018-01-15 16:45:18

标签: c++ c compiler-errors extern

我必须修改一个C项目,因为我现在需要使用一个C ++函数。

我们假设我有一个名为A.c的文件:

  

A.C

iron-scroll-threshold

以及其他也使用这些变量的文件,我们称之为B.c和C.c:

  

B.c

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <link rel="import" href="bower_components/polymer/polymer.html">
  <link rel="import" href="bower_components/iron-ajax/iron-ajax.html">
  <link rel="import" href="bower_components/iron-scroll-threshold/iron-scroll-threshold.html">
<script src="bower_components/webcomponentsjs/webcomponents-lite.js"></script>
</head>
<body>
  <test-component></test-component>
  <dom-module id="test-component">
  <template>
    <style>
      :host {
        display: block;
        height: 100%;
      }
      iron-scroll-threshold {
        height: 100%;
        overflow: auto;
      }
    </style>
    <iron-ajax auto url= "{{url}}"  last-response="{{response}}"></iron-ajax>
   <iron-scroll-threshold id="mytras" on-lower-threshold="loadMoreData" lower-threshold="100" scroll-target="document">
   <template is="dom-repeat" items="{{response.results}}">
     <span>&nbsp; [[index]] :  [[item.name.first]] [[item.name.last]]</span><br/><br/><br/>
   </template>  
   </iron-scroll-threshold>
  </template>
  <script>
    class MyTest extends Polymer.Element {
      static get is() { return 'test-component'; }
      static get properties() { return { 
        people:{
          type:Number,
          value:20
        }       
     }};
    static get observers() { return ['_url(people)']}
   _url(p){
      console.log(p);
      this.url = "https://randomuser.me/api?results=" + p;
      setTimeout(()=> {
                this.$.mytras.clearTriggers();
      },900)
   }

   loadMoreData (){
      console.log("God call me for every scroll");
      this.people += 10;                
   }
 }
customElements.define(MyTest.is, MyTest);
</script>
</dom-module>
</body>
</html>
  

C.c

uchar *const x;
uchar *const y;
/.../

当我用C编译器编译所有文件时,一切都很完美。 现在我需要使用一些C ++函数,所以我需要使用C ++编译器重新编译所有内容。这里有错误:

extern uchar *const x;
extern uchar *const y;
/.../
foo1(x);
bar1(y);

根据答案here中的建议,并在B.c和C.c中的变量周围使用extern uchar *const x; extern uchar *const y; /.../ foo1(x); bar1(y); 生成其他错误

关于如何解决这个问题的一些想法?

1 个答案:

答案 0 :(得分:0)

extern关键字应该放在头文件中,变量定义只需要在一个源文件中,所以你想要的是:

在A.h:

extern uchar *const x;
extern uchar *const y;

在A.c

uchar *const x;
uchar *const y;

在B.c

#include "A.h" 

void someFunction() {
    foo(x);
    bar(y);
}

在C.c

#include "A.h"

void someOtherFunction() {
    foo(x);
    bar(y);   
}
相关问题