Шаг за шагом, давайте изменим код OP, как он появляется сейчас (17 марта в 06:00 восточнее), после того, как OP применил несколько правок:
ШАГ 1:
Рассмотрим фрагмент 1,которая является прогой C ++ int main ().Компоновщик попытается сделать то, что вы хотите, то есть сделать squre_array () доступным - то есть вызываемым - из main ().В этом файле C ++ вы должны #include заголовочный файл, который объявляет squre_array () как язык C функция -единственная критическая точка во всем этом процессе, а не функция C ++.(Почему? Поскольку компилятор форматирует и хранит символы языка C по-другому, чем символы C ++; и поэтому, когда появляется компоновщик, символ типа C, определенный в источнике C, имеет вид , а не тот же как символ типа C ++, указанный в main ().) Теперь этот заголовочный файл называется cuda.h?Давайте предположим, что это так.Помните, что такое объявление делает "extern void squre_array ()" излишним и запутанным, поэтому уберите эту строку из этого исходного файла:
#include <string>
#include <iostream>
#include <stdio.h>
<strong>#include <cuda.h> <-- add this line</strong>
//extern void squre_array(); <strong><-- delete this line: we'll declare squre_array( ) in cuda.h</strong>
using namespace std;</p>
<p>int main() {
squre_array();
}
STEP 2:
Теперь рассмотрим фрагмент 2, который определяет функция squre_array ().Это простой старый C-код, поэтому мы должны заключить весь C-код в два набора по три строки в каждом.Эти шесть строк (всего) эффективно сообщают компоновщику, что символы в коде в квадратных скобках являются символами типа C, а не символами типа M ++.Когда компоновщик наконец убедится в этом, он может связать функцию squre_array () с вашей основной программой:
<br>
<strong>// insert magic three lines here, way up at the top of your .c file<br>
#ifdef __cplusplus //if we are compiling as C++, tell<br>
extern "C" { //the compiler that <em>this</em> stuff is plain old C<br>
#endif<br><br></strong>
#include <stdio.h><br>
#include <cuda.h> <strong><-- remember this "glue" file: we'll change it in step 3</strong><br></p>
<p><strong>//_<em>global</em>_ void square_array(float *a, int N) <-- remove the declaration,<br>
void square_array(float *a, int N) { <-- but retain the definition</strong> <br>
int idx = blockIdx.x * blockDim.x + threadIdx.x;<br>
if (idx
a[idx] = a[idx] * a[idx];<br>
}<br>
void squre_array()<br>
{<br>
float *a_h, *a_d;<br>
... <br>
cudaFree(a_d);<br>
}<br>
<strong>// close magic three lines<br>
#ifdef __cplusplus //<br>
} // closing curly bracket<br>
#endif<br><br></strong>
STEP 3:<br>The important thing that is missing from the OP's understanding is that squre_array( ) (and square_array( ), if you want) must be <strong>declared</strong>; and that declaration(s) need to be enclosed within the same pair of magic three lines. (OP: why must that be?) We decided in step 1 that the declaration would go in cuda.h. Or it can go in any .h file, but wherever it's declared, that .h file has to be #included in the file where main( ) resides (OP: again, why is this?). So let's fix up cuda.h:</p>
<p>
<strong>// magic three lines again<br>
#ifdef __cplusplus<br>
extern "C" {<br>
#endif<br></strong>
void squre_array();<br>
void square_array(float *a, int N);<br>
<strong>// close magic three lines, just like before<br>
#ifdef __cplusplus //<br>
} // closing curly bracket<br>
#endif<br><br></strong>
И все.Теперь ваша программа будет ссылаться.
- Пит