2015-01-06 7 views
3

Я начинаю использовать C. У меня есть проблема для определения глобальной переменной. Например. platformID используется в install.c. Я заявил в main.c, но все же у меня возникла ошибка:Как объявить глобальную переменную в C?

install.c | 64 | ошибка: 'platformID' uneclared (первое использование в этой функции) |

main.c:

#ifdef __APPLE__ 
#include <OpenCL/opencl.h> 
#else 
#include <CL/cl.h> 
#endif 

cl_int err;//the openCL error code/s 
cl_platform_id platformID;//will hold the ID of the openCL available platform 
cl_uint platformsN;//will hold the number of openCL available platforms on the machine 
cl_device_id deviceID;//will hold the ID of the openCL device 
cl_uint devicesN; //will hold the number of OpenCL devices in the system 

#include "include/types.h" 
#include "include/gaussian.h" 
#include "include/args.h" 
#include "include/files.h" 
#include "refu/Time/rfc_timer.h" 
#include <stdio.h> 

...

install.c

#include "include/types.h" 
#include "include/gaussian.h" 
#include <stdio.h> 
#include <stdlib.h> 
#include <stdbool.h> 

#include <sys/types.h> // mkdir 
#include <sys/stat.h> // mkdir 

#ifdef __APPLE__ 
#include <OpenCL/opencl.h> 
#else 
#include <CL/cl.h> 
#endif 

#define MAX_SOURCE_SIZE (1048576) //1 MB 
#define MAX_LOG_SIZE (1048576) //1 MB 

// Install: build kernel 
bool buildKernels(char ** path,FILES * files, int count) 
{ 

    int c; // number of file 

    if(clGetPlatformIDs(1, &platformID, &platformsN) != CL_SUCCESS) 
    { 
     printf("Could not get the OpenCL Platform IDs\n"); 
     return false; 
    } 
    if(clGetDeviceIDs(platformID, CL_DEVICE_TYPE_DEFAULT, 1,&deviceID, &devicesN) != CL_SUCCESS) 
    { 
     printf("Could not get the system's OpenCL device\n"); 
     return false; 
    } 

...

Как объявить глобальную переменную, так что видна в включенный файл? Можете ли вы помочь исправить это?

ответ

6
/* a.h */ 
extern int globali; /* Declaration for compilation */ 
/* Visible here */ 

Позже убедитесь, что вы определили (точно) один из единиц компиляции.

/* something.c */ 
int globali = 42; /* Definition for linking */ 
+1

Спасибо. У вас есть опечатка в имени переменной. Я разместил объявления в файле c и включил его. Если я переместю его в заголовок, который должен быть включен, я также должен переместить его? '#ifdef __APPLE__ #include #else #include #endif ' в заголовок? Сюда входят типы, которые я там использую. – user1141649

2

Добавьте одну строку

extern cl_platform_id platformID; 

до обращения к platformID в install.c.

2

Используйте extern перед использованием этой переменной в install.c. После этого скомпилируйте оба файла одновременно.

extern cl_platform_id platformID; 
2

добавить это в install.c перед использованием этой переменной

// external declaration for compilation 
extern cl_platform_id platformID; // It is defined in main.c file