Меню

Ошибка define not found

I am developing a library where the size of some variables depends on a #define and some #define which are created depending on the value of other #define.

e.g.

int variable1[SIZE_USER]
#if SIZE_USER>3
  #define CONDITION 1
#else
  #define CONDITION 0
#endif

The idea is that when a user wants to work with the library they create there own header file with all the preprocessor directives (#define) that are needed and uses this file in the same directory where there «main.cpp» file is and not inside the library source files.

The problem is that when I include the configuration file (which has all the #define’s) in the same directory where all my header files of the library are I do not have problems.

i.e.

#include <config.h>
//My Library Code...

But if I declare the configuration header file outside the source files of my Library the compiler doesn’t find the #define’s that were declared in the «main.cpp» file.

i.e.

#include<config.h>
#include<myLibrary.h>
//User code...

Is there something obvious I am missing on how the compiler is working?

Имеется проект на JavaScript + Node.JS + Ant.

Тесты для JavaScript-кода написаны на Karma + Jasmine.

Для оценки покрытия кода тестами используется Istanbul.

После ввода команды:
istanbul cover someFile.js
появляется ошибка:
«[path to the file]someFile.js:9
__cov_lhpa2MzHG9ur0fWhNQ3HsA.s[‘1’]++;define(‘some’,function(){__cov_lhpa2MzHG

ReferenceError: define is not defined»

Код внутри файла someFile.js:

define('someFile', function() {

    describe("Base64", function () {

        it('Base64_TestEncode', function () {

            expect( "TXkgZW5nbGlzaCBiYWQ=" ).toEqual( $ws.single.base64.encode( "someText" ) );

        });

    });

});

Подскажите, пожалуйста, как решить проблему?

UPD:

Добавил в начало файла код:

if (typeof define !== 'function') {
    var define = require('amdefine')(module);
}

Теперь выводится ошибка:
«[path to the file]someFile.js:9
pa2MzHG9ur0fWhNQ3HsA.f[‘1’]++;__cov_lhpa2MzHG9ur0fWhNQ3HsA.s[‘4’]++;describe(‘

ReferenceError: describe is not defined»

UPD_2:

Istanbul изначально поддерживается Karma.

Добавил в karma.konf.js строки:

preprocessors = {
  '<путь до файла someFile.js>': 'coverage'
}

reporters: ['progress', 'coverage']

coverageReporter: {
        type : 'html',
        dir : 'coverage/'
}

Если запустить karma.konf.js в WebStorm, то тесты проходят, но покрытие кода не выполняется (папка coverage не создается).

Если запустить karma.konf.js в PHPStorm, предварительно установив плагин «karma», то тесты проходят и покрытие кода выполняется (папка coverage создается).

Не смотря на это, в консоли при выполнении команды:
«istanbul cover <путь до файл someFile.js>»

появляются ошибки, описанные в начале вопроса.

  • Summary

  • Files

  • Reviews

  • Support

  • Tickets ▾

    • Feature Requests
    • Bugs
    • Patches
    • Users Contributions
    • Support Requests
  • News

  • Discussion

  • Code

  • Mailing Lists

  • svn

Menu

Procedure not found __define


Created:

2016-04-16

Updated:

2016-04-17

  • Andrew Cool

    Hi All,

    First post here. JUst downlaoded and installed the latest GDL 0.96 today.

    I’m trying to run a friend’s complicated OO program, but it’s falling over in it’s
    very first object definition routine with the error message :-

    % AVISTACK2::INIT: Procedure not found: DEFINE
    % Execution halted at: AVISTACK2::INIT 4298 F:IDLGDL_Avistack2avistack2
    define.pro
    % AVISTACK2 51 F:IDLGDL_Avistack2avistack2.pro
    % $MAIN$

    Now I’ve got avistack2.pro loaded — and it compiles.
    And I’ve got avistack2__define.pro loaded and it compiles too.

    But run avistack2, and she dies. All my files are in the same folder, and I’ve added that folder to !PATH.

    I should also point out that the program runs in everything version of IDL from IDL v6.4 onwards.

    This is running on Windows, if that makes a difference. Just in case, I’ve changed every filename
    to lowercase, although it shouldn’t be necessary?

    Running out of ideas, and generally desperate for Help.

    TIA,

    Andrew

    • GregJung

      Hi Andrew,

      % AVISTACK2::INIT: Procedure not found: DEFINE

      I was initially looking for a «define» routine before when I wasn’t very Object oriented.
      You message probably had «__DEFINE» as the procedure not found and the underscores
      were eaten by the formatter. I can reproduce that error if I try to create an object with
      a null-string name:

        retall
      ii=obj_new('')
      % Procedure not found: __DEFINE
      % Execution halted at: $MAIN$
      

      GDL is yet incomplete when compared against the more advanced IDL features; object programming is present, a solid foundation but missing a few items.
      A small example will make my point, from the coyote graphics package:

      cgc=obj_new('cgcoord')
      % Compiled module: CGCOORD__DEFINE.
      % Compiled module: CGCONTAINER__DEFINE.
      % CGCONTAINER__DEFINE: Procedure not found: IDL_CONTAINER__DEFINE
      % Execution halted at: CGCONTAINER__DEFINE   303 D:docsidlcoyotecgcontainer__define.pro
      %                      CGCOORD__DEFINE    239 D:docsidlcoyotecgcoord__define.pro
      %                      $MAIN$
      

      So IDL_CONTAINER is a hole in the lower-level OO programming.
      However IDL_OBJECT is valid, translated as a synonym for GDL_OBJECT.
      We have GDL_CONTAINER_NODEs but no working GDL_CONTAINERs, yet.

      I don’t think there are any show-stopper bugs in windows that wouldn’t also be seen in linux,
      —unless you venture into widgets.— Upon further review, since AVISTACK2 is firstly a big widget program, this is precisely the area of discrepant performance/functionalities between linux and windows versions. Gilles has only recently revamped the plot/widget framework, developing on linux with wxWidgets/gtk.

      Greg

       

      Last edit: GregJung 2016-04-20

      • Andrew Cool

        Hi Greg,

        Thanks for the reply. I don’t know that I can «build upo my experience with ‘what works'»
        as you say — the code I’m using is an enormous astronomy image processing packing
        that already exists, but is no longer under development. The author has agreed to Open Source it, but the folks willing to work on it do not have IDL licences, hence this attempt to see if GDL will do the trick.

        I’m somewhat surprised that the basic building block of Object definitions, the whole idea of having «myobject.pro» accompanied with «myobject__define.pro» is not catered for.

        In this particular program that I’m working with, there are no less than 50 object modules that use that fundamental method of Object definition.

        Are you saying that GDL, at the moment at least, cannot handle this pivotal object construct?

        Let me also state that I normally don’t go near Objects in IDL. If there’s an alternative way of
        defining the Objects without using «__define» files, then I’m all ears… 😉

        Regards,

        Andrew

  • giloo

    Hello,

    I’m sure that GDL handles basic object programming a la IDL, since the coyotelib graphic package works quite well.
    I would defintely not try that kind of huge oo code on the Windows port.
    The error message that you have may just be that the «__define» files are not found, and that may well be because of filenames incompatibilities. on windows, or a !PATH problem.
    I confirm that object.pro and object__define.pro are indeed associated in the GDL code.
    That’s almost all of my knowledge about objects in GDL or IDL.

  • Andrew Cool

    Hi giloo,

    I confirm that object.pro and object__define.pro are indeed associated in the GDL code.

    OK, that’s good to know. Thanks.

    All the object modules and their matching define files are in the same folder, which is pointed to GDL_Path, and confirmed by a print,!PATH.

    I’ll continue pottering to see if I can nail he problem…

    Thanks again,

    Andrew

  • Alain C.

    are you speaking about http://www.avistack.de/download.html ?

    you wrote :

    The author has agreed to Open Source it,

    where is the source code ?

    We are ready to test it …

    Would be great for this code and for GDL if it could work with GDL !

    Alain


Log in to post a comment.

У меня есть программа C с некоторыми определениями кодов ошибок. Нравится:

#define FILE_NOT_FOUND -2
#define FILE_INVALID -3 
#define INTERNAL_ERROR -4
#define ... 
#define ... 

Можно ли напечатать имя определения по его значению? Нравится:

PRINT_NAME(-2);

// output
FILE_NOT_FOUND

8 ответов

Короче говоря, нет. Самый простой способ сделать это будет примерно так (ПОЖАЛУЙСТА, ОБРАТИТЕ ВНИМАНИЕ: это предполагает, что вы никогда не сможете присвоить ошибке ноль/ноль):

 //Should really be wrapping numerical definitions in parentheses. 
#define FILE_NOT_FOUND  (-2)
#define FILE_INVALID    (-3) 
#define INTERNAL_ERROR  (-4)

typdef struct {
  int errorCode;
  const char* errorString;
} errorType;

const errorType[] = {
  {FILE_NOT_FOUND, "FILE_NOT_FOUND" },
  {FILE_INVALID,   "FILE_INVALID"   },
  {INTERNAL_ERROR, "INTERNAL_ERROR" },
  {NULL,           "NULL"           },
};

// Now we just need a function to perform a simple search
int errorIndex(int errorValue) {
  int i;
  bool found = false;
  for(i=0; errorType[i] != NULL; i++) {
    if(errorType[i].errorCode == errorValue) {
      //Found the correct error index value
      found = true;
      break;
    }
  }
  if(found) {
    printf("Error number: %d (%s) found at index %d",errorType[i].errorCode, errorType[i].errorString, i);
  } else {
    printf("Invalid error code provided!");
  }
  if(found) {
    return i;
  } else {
    return -1;
  }
}

Наслаждайтесь!

Кроме того, если вы хотите еще больше сэкономить на наборе текста, вы можете использовать макрос препроцессора, чтобы сделать его еще более аккуратным:

#define NEW_ERROR_TYPE(ERR) {ERR, #ERR}
 const errorType[] = {
      NEW_ERROR_TYPE(FILE_NOT_FOUND),
      NEW_ERROR_TYPE(FILE_INVALID),
      NEW_ERROR_TYPE(INTERNAL_ERROR),
      NEW_ERROR_TYPE(NULL)
    };

Теперь вам нужно ввести имя макроса только один раз, что снижает вероятность опечаток.


6

Cloud
5 Апр 2012 в 21:57

Вы можете сделать что-то подобное.

#include <stdio.h>

#define FILE_NOT_FOUND -2
#define FILE_INVALID -3 
#define INTERNAL_ERROR -4

const char* name(int value) {
#define NAME(ERR) case ERR: return #ERR;
    switch (value) {
        NAME(FILE_NOT_FOUND)
        NAME(FILE_INVALID)
        NAME(INTERNAL_ERROR)
    }
    return "unknown";
#undef NAME
}

int main() {
    printf("==== %d %s %sn", FILE_NOT_FOUND, name(FILE_NOT_FOUND), name(-2));
}


4

Ziffusion
16 Дек 2015 в 23:26

Нет, это невозможно. Что бы это напечатало?

#define FILE_NOT_FOUND   1
#define UNIT_COST        1
#define EGGS_PER_RATCHET 1

PRINT_NAME(1);


3

RichieHindle
5 Апр 2012 в 20:35

Как бы …

#define ERROR_CODE_1 "FILE_NOT_FOUND"
#define ERROR_CODE_2 "FILE_FOUND"

#define PRINT_NAME(N) ERROR_CODE_ ## N

Или же:

static char* error_codes(int err) {
   static char name[256][256] = {

   };
   int base = .... lowest error code;
   return name[err - base];
}

#define PRINT_NAME(N) error_code(N)


2

Anycorn
5 Апр 2012 в 20:39

Почему бы вместо этого не использовать перечисление?

enum errors {FILE_NOT_FOUND = -2, FILE_INVALID = -3, INTERNAL_ERROR = -4};

FILE *fp = fopen("file.txt", "r");


if(fp == NULL) {
    printf("Errorn");
    exit(FILE_NOT_FOUND);
}


1

Makoto
5 Апр 2012 в 20:45

Не автоматически. Имя при компиляции теряется, и в коде остается только постоянный номер.

Но вы можете построить что-то вроде этого:

const char * a[] = {"","","FILE_NOT_FOUND","FILE_INVALID"};

И получить к нему доступ, используя абсолютное значение определения значения в качестве индекса.


1

Flynch
5 Апр 2012 в 20:50

Используйте для этого назначенные инициализаторы C99, но необходимо соблюдать осторожность, если ваши коды ошибок отрицательные.

Сначала версия для положительных значений:

#define CODE(C) [C] = #C

static
char const*const codeArray[] = {
CODE(EONE),
CODE(ETWO),
CODE(ETHREE),
};

enum { maxCode = (sizeof codeArray/ sizeof codeArray[0]) };

Это выделяет массив нужной длины и с указателями на строки в правильных позициях. Обратите внимание, что стандартом разрешены повторяющиеся значения, последним будет то, которое фактически хранится в массиве.

Чтобы напечатать код ошибки, вам нужно проверить, меньше ли индекс maxCode.

Если ваши коды ошибок всегда отрицательные, вам просто нужно сбросить код перед печатью. Но, вероятно, было бы неплохо сделать это наоборот: сделать коды положительными и проверить возвращаемое значение на его знак. Если он отрицательный, код ошибки будет отрицанием значения.


1

Jens Gustedt
5 Апр 2012 в 22:53

Вот как я это делаю на C:

#pragma once 

#ifdef DECLARE_DEFINE_NAMES
// Switch-case macro for getting defines names
#define BEGIN_DEFINE_LIST  const char* GetDefineName (int key) { switch (key) {
#define MY_DEFINE(name, value)  case value: return #name;
#define END_DEFINE_LIST } return "Unknown"; }

#else

// Macros for declaring defines
#define BEGIN_COMMAND_LIST /* nothing */
#define MY_DEFINE(name, value)  static const int name = value;
#define END_COMMAND_LIST /* nothing */

#endif

// Declare your defines
BEGIN_DEFINE_LIST

MY_DEFINE(SUCCEEDED,       0)
MY_DEFINE(FAILED,         -1)
MY_DEFINE(FILE_NOT_FOUND, -2)
MY_DEFINE(INVALID_FILE,   -3)
MY_DEFINE(INTERNAL_ERROR  -4)
etc...

END_DEFINE_LIST
#pragma once
const char* GetDefineName(int key);
#define DECLARE_DEFINE_NAMES
#include "MyDefines.h"

Теперь вы можете использовать объявленный макрос switch-case где угодно, например:

< Где Всегда.c >

#include "MyDefines.h"
#include "MyDefineInfo.h"

void PrintThings()
{
    Print(GetDefineName(SUCCEEDED));
    Print(GetDefineName(INTERNAL_ERROR));
    Print(GetDefineName(-1);
    // etc.
}


0

JKallio
16 Дек 2015 в 20:22

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
#include <windows.h>
#include <stdio.h>

#include "../license.h"

// add a license
// addlicense.exe file:<filename> add bbuser:<username> bbpass:<password> serial:<serialNumber> access:<accesskey> pass:<gcpassword> priv:<privileges>

// delete a license
// addlicense.exe file:<filename> delete find:<options>

// modify a license
// addlicense.exe file:<filename> modify find:<options> <newoptions>

// unban a license
// addlicense.exe file:<filename> unban find:<options>

// display a license
// addlicense.exe file:<filename> info find:<options>

// parses a command line option.
DWORD parseoption(LICENSE* l,char* option)
{
    if (!memcmp(option,"bbuser:",7))
    {
        strcpy(l->username,&option[7]);
        return LICENSE_CHECK_USERNAME;
    } else if (!memcmp(option,"bbpass:",7))
    {
        strcpy(l->password,&option[7]);
        return LICENSE_CHECK_PASSWORD;
    } else if (!memcmp(option,"serial:",7))
    {
        if ((option[7] == '0') && ((option[8] == 'x') || (option[8] == 'X'))) sscanf(&option[9],"%X",&l->serialNumber);
        else sscanf(&option[7],"%d",&l->serialNumber);
        return LICENSE_CHECK_SERIALNUMBER;
    } else if (!memcmp(option,"access:",7))
    {
        strcpy(l->accessKey,&option[7]);
        return LICENSE_CHECK_ACCESSKEY;
    } else if (!memcmp(option,"pass:",5))
    {
        strcpy(l->password2,&option[5]);
        return LICENSE_CHECK_GC_PASSWORD;
    } else if (!memcmp(option,"priv:",5))
    {
        if ((option[5] == '0') && ((option[6] == 'x') || (option[6] == 'X'))) sscanf(&option[7],"%X",&l->privileges);
        else sscanf(&option[5],"%d",&l->privileges);
        return LICENSE_CHECK_PRIVILEGES;
    }
    return 0;
}

DWORD scanFlags = 0,replaceFlags = 0;

int deletelicenseenumproc(LICENSE_LIST* list,int index,LICENSE* l,long param)
{
    bool success;
    if (DeleteLicense(list,index))
    {
        printf("> > license deleted: %08Xn",l->serialNumber);
        return (-1);
    }
    printf("> > license could not be deleted: %08Xn",l->serialNumber);
    return 1;
}

int modifylicenseenumproc(LICENSE_LIST* list,int index,LICENSE* l,LICENSE* lnew)
{
    bool success;
    printf("> > license modified: %08Xn",l->serialNumber);
    if (replaceFlags & LICENSE_CHECK_USERNAME) strcpy(l->username,lnew->username);
    if (replaceFlags & LICENSE_CHECK_PASSWORD) strcpy(l->password,lnew->password);
    if (replaceFlags & LICENSE_CHECK_SERIALNUMBER) l->serialNumber = lnew->serialNumber;
    if (replaceFlags & LICENSE_CHECK_ACCESSKEY) strcpy(l->accessKey,lnew->accessKey);
    if (replaceFlags & LICENSE_CHECK_GC_PASSWORD) strcpy(l->password2,lnew->password2);
    if (replaceFlags & LICENSE_CHECK_PRIVILEGES) l->privileges = lnew->privileges;
    return 1;
}

int unbanlicenseenumproc(LICENSE_LIST* list,int index,LICENSE* l,long param)
{
    bool success;
    memset(&l->banTime,0,sizeof(FILETIME));
    printf("> > license unbanned: %08Xn",l->serialNumber);
    return 1;
}

int infolicenseenumproc(LICENSE_LIST* list,int index,LICENSE* l,long param)
{
    bool success;
    printf("> blue burst user/pass: %s %sn",l->username,l->password);
    printf("> gc serial/access/password: %08X %s %sn",l->serialNumber,l->accessKey,l->password2);
    printf("> privilege flags/ban time: %08X %08X%08Xnn",l->privileges,l->banTime.dwHighDateTime,l->banTime.dwLowDateTime);
    return 1;
}

int main(int argc,char* argv[])
{
    printf("> fuzziqer software newserv license editornn");

    char filename[MAX_PATH];
    DWORD x,flagsTemp;
    LICENSE_LIST* list;
    LICENSE lold,lnew;
    memset(&lold,0,sizeof(LICENSE));
    memset(&lnew,0,sizeof(LICENSE));

    bool result;
    DWORD action = 0; // 1 = add, 2 = delete, 3 = modify, 4 = unban, 5 = get info
    DWORD numFailures = 0,numChanges;
    for (x = 1; x < argc; x++)
    {
        result = true;
             if (!memcmp(argv[x],"add",3)) action = 1;
        else if (!memcmp(argv[x],"delete",6)) action = 2;
        else if (!memcmp(argv[x],"modify",6)) action = 3;
        else if (!memcmp(argv[x],"unban",5)) action = 4;
        else if (!memcmp(argv[x],"info",4)) action = 5;
        else if (!memcmp(argv[x],"file:",5)) strcpy(filename,&argv[x][5]);
        else if (!memcmp(argv[x],"find:",5))
        {
            flagsTemp = parseoption(&lold,&argv[x][5]);
            if (!flagsTemp)
            {
                printf("> > error: unknown find option: %sn",&argv[x][5]);
                numFailures++;
            } else scanFlags |= flagsTemp;
        } else {
            flagsTemp = parseoption(&lnew,argv[x]);
            if (!flagsTemp)
            {
                printf("> > error: unknown option: %sn",argv[x]);
                numFailures++;
            } else replaceFlags |= flagsTemp;
        }
    }

    list = LoadLicenseList(filename);
    if (!list)
    {
        printf("> > warning: license file not found, creating a new onen");
        list = CreateLicenseList();
        if (!list)
        {
            printf("> > use the [file:<filename>] option to specify the file namen");
            numFailures++;
        } else strcpy(list->filename,filename);
    }
    if (numFailures) return (-1);

    switch (action)
    {
      case 1: // add license
        if (AddLicense(list,&lnew)) printf("> > license addedn");
        else printf("> > error!n");
        break;
      case 2: // delete license
        if (!scanFlags) printf("> > error: no scan flags specifiedn> > use at least one [find:] directiven");
        else {
            numChanges = EnumLicenses(list,scanFlags,&lold,(LicenseEnumProc)deletelicenseenumproc,0);
            printf("> > %d licenses deletedn",numChanges);
        }
        break;
      case 3: // modify license
        if (!scanFlags) printf("> > error: no scan flags specifiedn> > use at least one [find:] directiven");
        else {
            numChanges = EnumLicenses(list,scanFlags,&lold,(LicenseEnumProc)modifylicenseenumproc,(long)(&lnew));
            printf("> > %d licenses modifiedn",numChanges);
        }
        break;
      case 4: // unban license
        if (!scanFlags) printf("> > error: no scan flags specifiedn> > use at least one [find:] directiven");
        else {
            numChanges = EnumLicenses(list,scanFlags,&lold,(LicenseEnumProc)unbanlicenseenumproc,0);
            printf("> > %d licenses unbannedn",numChanges);
        }
        break;
      case 5: // show license
        if (!scanFlags) printf("> > error: no scan flags specifiedn> > use at least one [find:] directiven");
        else {
            numChanges = EnumLicenses(list,scanFlags,&lold,(LicenseEnumProc)infolicenseenumproc,0);
            printf("> > %d licenses listedn",numChanges);
        }
        break;
    }
    if (!SaveLicenseList(list)) printf("> > error: couldn't save the license listn");

    system("PAUSE>NUL");

    return 0;
}

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Ошибка defaults loaded как исправить
  • Ошибка default radeon wattman settings have been restored due to an unexpected system failure