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
-
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_Avistack2avistack2define.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
-
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
-
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
-
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.
-
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
-
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
|
|