Общие заголовки src/Include

Назначение

Каталог src/Include — общие заголовки расчётной части пакета. Их подключают библиотеки (src/libs/*), ядра (src/kernels/*) и вьюверы (src/viewers/*). Каталог передаётся компилятору как путь поиска, поэтому заголовки включаются в угловых скобках: #include <typedef.h>.

Заголовки делятся на три группы:

  1. Действующие заголовки Qt6-версии — описывают код, который собирается и работает: типы, библиотеки complex, exprint, sfile95, prepr, TMCLibError, TMCIndan, ядра, вьюверы, GPU.
  2. Унаследованные объявления TAMIC — заголовки, которые подключаются из действующего кода (обычно ради цепочки включений), но объявляют функции, не определённые нигде в исходниках пакета. Подробнее — ниже.
  3. Заголовки вне сборки — не подключаются ни одним компилируемым файлом; хранятся для сверки со старыми версиями. Список — в разделе «Вне сборки».

Почти все заголовки — наследие пакета TAMIC (DOS, начало 1990-х): отсюда пустые модификаторы _far, _fortran, обращение к «окнам статистики» и «листингу».

Карта заголовков

Заголовки Что в них Страница
typedef.h базовые типы _real, _complex, Uint, DWORD, физические константы ниже
typerth.h, tmcidx.h, tmclimit.h, label/rth.h типы и пределы ядер Rt-сетки, тип номера узла, метки файлов ядро H, TMCIndan
complex1.h комплексная арифметика complex
expr.h, inter.h вычислитель выражений и интерпретатор формул Expr, Inter
s_file.h, proc_s.h, frqdata.h, ys_proc.h, listing.h файлы S-матриц, таблица частот, листинг sfile95
prepr1.h препроцессор задания .tpl prepr
tmcliberror.h объект ошибки CTmcLibError TMCLibError
tmcrth_*.h, fieldintegrated.h, indan/* чтение задания, топология, порты, поле для ДН TMCIndan
tmcgraph.h, tmcgrviw.h, tmcgrexpression.h, tmcsmatrix.h, tmcttos.h, tmcwideband.h графики и обработка сигналов во вьюверах TMCGROUT, TMCROS
tmcocl.h, tmccalctiming.h, cl/* расчёт на видеокарте (OpenCL), хронометраж GPU
error1.h числовые коды ошибок TAMIC ниже
tmc_lib.h функции памяти и служебная библиотека TAMIC ниже
postpro.h таблица входов INPUT_DATA, описание S-файла S_INDEX, графики DOS ниже
compfile.h, datacnst.h, descrptr.h, indan.h, indandec.h, linklist.h, mainwndw.h, matrix.h, run.h, run_flag.h, tpl_file.h, h_e/debug.h унаследованные объявления TAMIC ниже

typedef.h — базовые типы

typedef.h подключается почти всеми файлами src/libs, src/kernels, src/viewers. Главное, что он задаёт:

Имя Значение в сборке Комментарий
_HIGH_ACCURACY определён включает двойную точность
_real double основной вещественный тип расчётной части
REAL_MAX, REAL_MIN, REAL_EPSILON, REAL_DIG DBL_MAX, DBL_MIN, DBL_EPSILON, DBL_DIG пределы _real
_NDP2 определён признак «не 16-битная DOS»
_far, _near, _huge, _fortran, _pascal, _cdecl пустые модификаторы 16-битных компиляторов, ничего не меняют
_static_ static
Uchar, BYTE, Uint, WORD, Ulong, DWORD беззнаковые целые DWORD — unsigned long: 32 бита в Windows, 64 бита в 64-битном Linux
INT_1 short элементы таблицы входов INPUT_DATA (2 байта)
FILENAME, FILENAME_MAX 13 и системное значение длины имени DOS 8.3 и пути
FILE_LIST структура имя, путь и диск файла (DOS)
MU_NUL 12.56637·10−7 Гн/м магнитная постоянная μ0
EPSILON_NUL 8.85418757·10−12 Ф/м электрическая постоянная ε0
LIGHT_VEL 2.99792458·108 м/с скорость света
PI 3.141592653589793 если не задано ранее
isnumber(c), rsign(x) макросы «символ может входить в число», знак ±1

Тип _complex (структура с полями x — действительная часть, y — мнимая) для файлов на C определяется здесь же, а для C++ приходит из <math.h> MinGW или из преамбулы compat/include/tmc_win_prelude.h, которую компилятор подставляет в начало каждого файла src/libs, src/kernels, src/viewers (флаг -include).

Обозначения величин и единицы в теории: обозначения и единицы.

error1.h — коды ошибок TAMIC

error1.h содержит около 350 числовых кодов ошибок, сгруппированных по тысячам:

Диапазон Область
0001, 1001 память
2001–2006 временные файлы, файл задания, листинг
2100–2107 справочная система DOS
2200–2221 файлы TWP и Y-матриц
2300–2313 файлы S-матриц
2401–2420 выражения (2400 + n, где -n — код Expr)
2501–2517 препроцессор
3001–3002, 4001–4007 DOS, диски и пути
5001–5113, 5400–5403 разбор задания, частоты, единицы, RGF-файлы
5200–5510 коды моделей TAMIC H/E, IC, M — под #if, в сборке не активны
6001–6302, 7001, 7501, 8001–8010 база данных, связи блоков, печать, расчёт

Коды передаются в put_error_messege(int код, ...). В Qt6-версии эта функция (sfile95, errors.cpp) — заглушка: тело закомментировано, она ничего не выводит и возвращает 0. Поэтому числовые коды служат лишь метками в коде, а пользователь видит ошибки только через текстовый объект CTmcLibError или через текст ошибки препроцессора.

Вторая перегрузка, put_error_messege(char *текст), определена в препроцессоре (prep_mn.cpp) и копирует текст в его буфер ошибки — см. ошибки препроцессора. Макрос put_error_message — синоним с исправленным написанием.

tmc_lib.h — память и служебные функции

Из длинного списка объявлений tmc_lib.h в Qt6-версии определены и используются только функции памяти (они находятся в sfile95, s_memf.cpp):

Функция Поведение
alloc_mem_err(size) malloc(size); при неудаче вызывает put_error_messege(FATAL_MEM_ALLOC_ERROR) (заглушку) и возвращает NULL
free_mem(ptr) free(ptr), возвращает 0
free_mem_null(&ptr) освобождает блок, если ptr != NULL, и обнуляет указатель

Ими пользуются sfile95 и препроцессор. Из-за того что функции памяти живут в sfile95, а put_error_messege(char*) — в prepr, эти две библиотеки зависят друг от друга и линкуются группой (см. sfile95).

Остальное — функции имён файлов, дисков DOS, допусков сравнения, геометрии на Фортране, паузы и вывода в строку экрана — объявлено, но не определено.

postpro.h — входы и описание S-файла

postpro.h подключается из s_file.h, поэтому его видят все пользователи sfile95. Действующие сущности:

Сущность Смысл
INPUT_DATA таблица входов многополюсника: num — число входов, array[i] — число мод на входе i, dim — порядок S-матрицы (суммарное число мод). Поля типа INT_1 (short). Хранится в заголовке файла .s
S_INDEX имена файла задания и S-файла и три шага сетки (используется в sfile95)
put_S_table печать таблицы S-матрицы в листинг (sfile95, s_table.cpp); в Qt6-версии не вызывается

Структуры графиков (MARKER, CURVE, CURVE_INDEX, GRAPH_CURVE, GRAPH_WND_CONFIG …) и функции меню и рисования относятся к DOS-версии и в пакете не определены. Графики в Qt6-версии строят вьюверы.

У заголовка нет защиты от повторного включения. Часть структур защищена собственными макросами (_INPUT_DATA_DEF, _S_INDEX_DEF, _MARKER, _CURVE_INDEX), но graph_curve, _real_point, curve_data и graph_wnd_config — нет: второе включение postpro.h в один файл даёт ошибку «redefinition of struct …». Обычно заголовок приходит через s_file.h, у которого защита есть.

Унаследованные объявления TAMIC

Заголовки этой группы включаются из действующего кода, но большинство объявленных в них функций нигде в исходниках пакета не определены. Сборка при этом проходит: функции не вызываются, а немногие вызовы находятся в функциях, которые сами никем не вызываются (например, make_S_matrix_name в sfile95), и такие объектные модули компоновщик из статической библиотеки не подтягивает.

Заголовок Содержание Что реально определено
compfile.h имя и флаг «файла сравнения» S-матрицы get_comp_file_flag — заглушка, всегда 0
datacnst.h шаг, высота, точность, eps и mu задания ничего
descrptr.h описатели разделов задания (#STEP, #OUTPUT, #EOF …) и их коды M_* ничего
indan.h загрузка шага, атрибуты, вывод, путь #include SetIncludePathName/GetIncludePathName — только в prepr/incpath.cpp вне сборки
indandec.h модули схемы TAMIC: входы, волноводы, шлейфы, многоугольники только структуры, в коде не используются
linklist.h список связей между модулями ничего
mainwndw.h окно статистики DOS, пункты ST_ITEMS stat_messege — пустая заглушка
matrix.h обращение, разложение, собственные значения, Z/Y/S Check_S_Unitary — только в sfile95/read_s1.cpp вне сборки
run.h Y-матрица, модули, подпрограммы МКЭ (Фортран) ничего
run_flag.h флаги этапов расчёта, номер шага задания ничего
tpl_file.h построчное чтение задания DOS fget_tpl_line — только в prepr/dr_buf.cpp вне сборки
h_e/debug.h флаги отладочной печати ничего
tmc_lib.h см. выше функции памяти
error1.h см. выше put_error_messege (две перегрузки)

В комментариях к таким функциям стоит пометка «Определения в исходниках пакета нет». Параметры подпрограмм метода конечных элементов TAMIC в run.h (Trangl, GnAnsm, FEMat, TRNSK, MODNK …) поимённо не описаны: их смысл кодом пакета не раскрыт.

Правило для нового кода: не вызывайте функции из этих заголовков, не проверив, что у них есть определение, — иначе ошибка проявится только при линковке программы.

Заголовки вне сборки

Эти заголовки не включает ни один компилируемый файл Qt6-версии (некоторые подключаются только под #ifdef моделей TAMIC, которые в сборке не определены). Каждый помечен в шапке фразой «В сборку Qt6-версии не входит».

Группа Заголовки
Трёхмерная модель TAMIC 3d/*, 3d_calc.h, 3d_error.h, 3d_limit.h, dataload.h, tmc3dgr.h, descript/3d.h, label/3d.h
Модели H/E, W, TWP descript/h_e.h, descript/w.h, label/e.h, label/h.h, label/w.h, label/twp.h, w/debug.h, debug.h, tamic_h.h, h_proc.h, operator.h, topology.h, twp_file.h
Модель M (микрополоски) m/*, descript/m.h, label/m.h
Модель IC mic/*, descript/ic.h, label/ic.h, modeflag.h, str_com.h
Y-матрицы и фильтры y_file.h, y_fltr.h, y_matr4.h
Классы C++ TAMIC _complex.hpp, file_cpp.hpp, offs_cpp.hpp, s_array.hpp, s_file.hpp, s_input.hpp
Интерфейс DOS textlib.h, mouse.h, keybd.h, help.h, print.h, sound.h, init.h, tmc.h, getargen.h, dos_time.h, ndp_dos.h, file.h, pedit.h, peditdec.h, lock.h, pragma.h
База задания и постобработка DOS attribut.h, commblck.h, def_mcci.h, inptabdb.h, load_db.h, longdata.h, optimiz.h, postpro/*
Классы MFC-версии без реализации integralforcemomforce.h, splanefieldapproch.h, splaneone.h
MFC-версия tmcdoclink.h — ссылка на документацию из окна «О программе»; в Qt6-версии ту же задачу решает gui_common/aboutbox

Внимание: topology.h из этого каталога и одноимённый apps/fieldview_rhi/src/core/topology.h — разные файлы.

Подводные камни

  1. expr.h не защищён от повторного включения. inter.h сам включает expr.h, поэтому оба заголовка в одном файле дают ошибку «conflicting declaration EXPR_THREAD_CTX». Подключайте один из них.
  2. postpro.h нельзя включать в один файл дважды — см. postpro.h. error1.h защиты тоже не имеет, но повторное включение безопасно: макросы переопределяются тем же значением, а объявления функций можно повторять.
  3. DWORD — unsigned long, а не 32-битное целое: в 64-битном Linux он занимает 8 байт. Для данных в файлах используйте типы фиксированного размера.
  4. Объявление — не определение. Многие функции объявлены, но не определены (см. унаследованные объявления).

Shared headers src/Include

Purpose

The directory src/Include holds the shared headers of the computational part of the package. They are included by the libraries (src/libs/*), the kernels (src/kernels/*) and the viewers (src/viewers/*). The directory is passed to the compiler as a search path, so the headers are included in angle brackets: #include <typedef.h>.

The headers fall into three groups:

  1. Active headers of the Qt6 version — they describe code that is built and works: types, the complex, exprint, sfile95, prepr, TMCLibError, TMCIndan libraries, the kernels, the viewers, GPU.
  2. Legacy TAMIC declarations — headers that are included from active code (usually for the sake of the include chain) but declare functions that are not defined anywhere in the package sources. See below for details.
  3. Headers outside the build — not included by any compiled file; kept for comparison with old versions. The list is in the section "Outside the build".

Almost all headers are a legacy of the TAMIC package (DOS, early 1990s): hence the empty modifiers _far, _fortran, and references to "statistics windows" and the "listing".

Header map

Headers What they contain Page
typedef.h basic types _real, _complex, Uint, DWORD, physical constants below
typerth.h, tmcidx.h, tmclimit.h, label/rth.h types and limits of the Rt-grid kernels, the node index type, file labels H kernel, TMCIndan
complex1.h complex arithmetic complex
expr.h, inter.h expression evaluator and formula interpreter Expr, Inter
s_file.h, proc_s.h, frqdata.h, ys_proc.h, listing.h S-matrix files, frequency table, listing sfile95
prepr1.h .tpl task-file preprocessor prepr
tmcliberror.h error object CTmcLibError TMCLibError
tmcrth_*.h, fieldintegrated.h, indan/* task-file reading, topology, ports, field for the RP TMCIndan
tmcgraph.h, tmcgrviw.h, tmcgrexpression.h, tmcsmatrix.h, tmcttos.h, tmcwideband.h plots and signal processing in the viewers TMCGROUT, TMCROS
tmcocl.h, tmccalctiming.h, cl/* GPU computing (OpenCL), timing GPU
error1.h TAMIC numeric error codes below
tmc_lib.h memory functions and the TAMIC utility library below
postpro.h input table INPUT_DATA, S-file description S_INDEX, DOS plots below
compfile.h, datacnst.h, descrptr.h, indan.h, indandec.h, linklist.h, mainwndw.h, matrix.h, run.h, run_flag.h, tpl_file.h, h_e/debug.h legacy TAMIC declarations below

typedef.h — basic types

typedef.h is included by almost all src/libs, src/kernels, src/viewers files. The main things it defines:

Name Value in the build Comment
_HIGH_ACCURACY defined enables double precision
_real double the main floating-point type of the computational part
REAL_MAX, REAL_MIN, REAL_EPSILON, REAL_DIG DBL_MAX, DBL_MIN, DBL_EPSILON, DBL_DIG limits of _real
_NDP2 defined "not 16-bit DOS" flag
_far, _near, _huge, _fortran, _pascal, _cdecl empty modifiers of 16-bit compilers, change nothing
_static_ static
Uchar, BYTE, Uint, WORD, Ulong, DWORD unsigned integers DWORD is unsigned long: 32 bits on Windows, 64 bits on 64-bit Linux
INT_1 short elements of the input table INPUT_DATA (2 bytes)
FILENAME, FILENAME_MAX 13 and the system value lengths of a DOS 8.3 name and of a path
FILE_LIST structure file name, path and drive (DOS)
MU_NUL 12.56637·10−7 H/m magnetic constant μ0
EPSILON_NUL 8.85418757·10−12 F/m electric constant ε0
LIGHT_VEL 2.99792458·108 m/s speed of light
PI 3.141592653589793 unless defined earlier
isnumber(c), rsign(x) macros "the character may be part of a number", sign ±1

The _complex type (a structure with fields x — real part, y — imaginary part) is defined here for C files, while for C++ it comes from MinGW's <math.h> or from the prelude compat/include/tmc_win_prelude.h, which the compiler inserts at the beginning of every src/libs, src/kernels, src/viewers file (the -include flag).

Notation of quantities and units in the theory: notation and units.

error1.h — TAMIC error codes

error1.h contains about 350 numeric error codes grouped by thousands:

Range Area
0001, 1001 memory
2001–2006 temporary files, task file, listing
2100–2107 DOS help system
2200–2221 TWP and Y-matrix files
2300–2313 S-matrix files
2401–2420 expressions (2400 + n, where -n is the Expr code)
2501–2517 preprocessor
3001–3002, 4001–4007 DOS, drives and paths
5001–5113, 5400–5403 task-file parsing, frequencies, units, RGF files
5200–5510 codes of the TAMIC H/E, IC, M models — under #if, not active in the build
6001–6302, 7001, 7501, 8001–8010 database, block links, printing, computation

The codes are passed to put_error_messege(int code, ...). In the Qt6 version this function (sfile95, errors.cpp) is a stub: its body is commented out, it outputs nothing and returns 0. Therefore the numeric codes serve only as markers in the code, and the user sees errors only through the text object CTmcLibError or through the preprocessor error text.

The second overload, put_error_messege(char *text), is defined in the preprocessor (prep_mn.cpp) and copies the text into its error buffer — see preprocessor errors. The macro put_error_message is a synonym with the corrected spelling.

tmc_lib.h — memory and utility functions

Of the long list of declarations in tmc_lib.h, the Qt6 version defines and uses only the memory functions (they are in sfile95, s_memf.cpp):

Function Behaviour
alloc_mem_err(size) malloc(size); on failure calls put_error_messege(FATAL_MEM_ALLOC_ERROR) (the stub) and returns NULL
free_mem(ptr) free(ptr), returns 0
free_mem_null(&ptr) frees the block if ptr != NULL and zeroes the pointer

They are used by sfile95 and the preprocessor. Because the memory functions live in sfile95, while put_error_messege(char*) lives in prepr, these two libraries depend on each other and are linked as a group (see sfile95).

The rest — functions for file names, DOS drives, comparison tolerances, Fortran geometry, pauses and output to a screen line — is declared but not defined.

postpro.h — inputs and S-file description

postpro.h is included from s_file.h, so all users of sfile95 see it. Active entities:

Entity Meaning
INPUT_DATA input table of the multiport: num — number of ports, array[i] — number of modes at port i, dim — order of the S-matrix (total number of modes). Fields of type INT_1 (short). Stored in the header of the .s file
S_INDEX names of the task file and the S-file and three grid steps (used in sfile95)
put_S_table printing of the S-matrix table to the listing (sfile95, s_table.cpp); not called in the Qt6 version

The plot structures (MARKER, CURVE, CURVE_INDEX, GRAPH_CURVE, GRAPH_WND_CONFIG …) and the menu and drawing functions belong to the DOS version and are not defined in the package. In the Qt6 version plots are drawn by the viewers.

The header has no include guard. Some structures are protected by their own macros (_INPUT_DATA_DEF, _S_INDEX_DEF, _MARKER, _CURVE_INDEX), but graph_curve, _real_point, curve_data and graph_wnd_config are not: a second inclusion of postpro.h in one file gives the error "redefinition of struct …". Usually the header comes through s_file.h, which does have a guard.

Legacy TAMIC declarations

The headers of this group are included from active code, but most of the functions declared in them are not defined anywhere in the package sources. The build still succeeds: the functions are not called, and the few calls are located in functions that are themselves never called (for example, make_S_matrix_name in sfile95), and the linker does not pull such object modules out of the static library.

Header Contents What is actually defined
compfile.h name and flag of the S-matrix "comparison file" get_comp_file_flag — a stub, always 0
datacnst.h step, height, accuracy, eps and mu of the task file nothing
descrptr.h descriptors of task-file sections (#STEP, #OUTPUT, #EOF …) and their codes M_* nothing
indan.h step loading, attributes, output, the #include path SetIncludePathName/GetIncludePathName — only in prepr/incpath.cpp, outside the build
indandec.h TAMIC circuit modules: ports, waveguides, stubs, polygons structures only, not used in the code
linklist.h list of links between modules nothing
mainwndw.h DOS statistics window, items ST_ITEMS stat_messege — an empty stub
matrix.h inversion, decomposition, eigenvalues, Z/Y/S Check_S_Unitary — only in sfile95/read_s1.cpp, outside the build
run.h Y-matrix, modules, FEM subroutines (Fortran) nothing
run_flag.h computation stage flags, task-file step number nothing
tpl_file.h line-by-line reading of a DOS task file fget_tpl_line — only in prepr/dr_buf.cpp, outside the build
h_e/debug.h debug-print flags nothing
tmc_lib.h see above memory functions
error1.h see above put_error_messege (two overloads)

The comments on such functions carry the note "There is no definition in the package sources". The parameters of the TAMIC finite-element subroutines in run.h (Trangl, GnAnsm, FEMat, TRNSK, MODNK …) are not described by name: their meaning is not revealed by the package code.

Rule for new code: do not call functions from these headers without checking that they have a definition — otherwise the error will only show up when the program is linked.

Headers outside the build

These headers are not included by any compiled file of the Qt6 version (some are included only under #ifdef of TAMIC models that are not defined in the build). Each is marked in its header comment with the phrase "Not part of the Qt6 version build".

Group Headers
TAMIC three-dimensional model 3d/*, 3d_calc.h, 3d_error.h, 3d_limit.h, dataload.h, tmc3dgr.h, descript/3d.h, label/3d.h
H/E, W, TWP models descript/h_e.h, descript/w.h, label/e.h, label/h.h, label/w.h, label/twp.h, w/debug.h, debug.h, tamic_h.h, h_proc.h, operator.h, topology.h, twp_file.h
M model (microstrips) m/*, descript/m.h, label/m.h
IC model mic/*, descript/ic.h, label/ic.h, modeflag.h, str_com.h
Y-matrices and filters y_file.h, y_fltr.h, y_matr4.h
TAMIC C++ classes _complex.hpp, file_cpp.hpp, offs_cpp.hpp, s_array.hpp, s_file.hpp, s_input.hpp
DOS interface textlib.h, mouse.h, keybd.h, help.h, print.h, sound.h, init.h, tmc.h, getargen.h, dos_time.h, ndp_dos.h, file.h, pedit.h, peditdec.h, lock.h, pragma.h
DOS task database and post-processing attribut.h, commblck.h, def_mcci.h, inptabdb.h, load_db.h, longdata.h, optimiz.h, postpro/*
MFC-version classes without implementation integralforcemomforce.h, splanefieldapproch.h, splaneone.h
MFC version tmcdoclink.h — documentation link from the About dialog; in the Qt6 version the same task is handled by gui_common/aboutbox

Note: topology.h from this directory and the identically named apps/fieldview_rhi/src/core/topology.h are different files.

Pitfalls

  1. expr.h has no include guard. inter.h itself includes expr.h, so having both headers in one file gives the error "conflicting declaration EXPR_THREAD_CTX". Include only one of them.
  2. postpro.h must not be included twice in one file — see postpro.h. error1.h has no guard either, but repeated inclusion is safe: the macros are redefined with the same value, and function declarations may be repeated.
  3. DWORD is unsigned long, not a 32-bit integer: on 64-bit Linux it occupies 8 bytes. For data in files use fixed-size types.
  4. A declaration is not a definition. Many functions are declared but not defined (see legacy declarations).