簡體   English   中英

如何使用 extern 在 C++ 和 CUDA 中聲明/定義全局變量

[英]How to use extern for declaring/defining global variable in C++ and CUDA

我有以下由一個.cpp、一個.cu和一個.hxx組成的代碼結構

實用程序.hxx

#ifndef UTILITIES_HXX
#define UTILITIES_HXX

namespace B{

extern int doors;
}

文件2.cu

#include "utilities.hxx"

namespace A {

int foo (){
    switch(B::doors){
    //do something
    }
}
}

文件3.cxx

#include "utilities.hxx"

namespace B{

int doors=-1;

class Vehicle{
public:
  void operation() {
      doors++;
      A::foo();
      doors++;
      A::foo();
  }
}
}

我在標頭中將門變量聲明為 extern,並在 .cxx 文件中定義它。 所以在那之后,第二個 .cpp 應該可以使用它了。 但是,鏈接時出現以下錯誤:

/usr/bin/ld: ../src/libapp.a(FILE2.cu.o): 在函數A::foo(void)': /MYPATH/FILE2.cu:19: undefined reference to '

我究竟做錯了什么? 實際上 FILE2.cu 中的 foo 函數是一個普通的 C++ 函數,根本不涉及 CUDA。

缺少#endif ,缺少return語句,沒有A::foo()原型,缺少分號

這些更改似乎對我有用:

$ cat utilities.hxx
#ifndef UTILITIES_HXX
#define UTILITIES_HXX

namespace B{

extern int doors;
}
#endif
$ cat file2.h

namespace A {

int foo ();
}
$ cat file2.cu
#include "utilities.hxx"

namespace A {

int foo (){
    switch(B::doors){
    //do something
    }
    return 0;
}
}
$ cat file3.cpp
#include "utilities.hxx"
#include "file2.h"
namespace B{

int doors=-1;

class Vehicle{
public:
  void operation() {
      doors++;
      A::foo();
      doors++;
      A::foo();
  }
};
}

$ nvcc -shared file2.cu file3.cpp -Xcompiler -fPIC
$ nvcc -lib file2.cu file3.cpp 
$ 

我只能使用您所展示的內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM