glideapps/quicktype

[FEATURE]: cJSON - generate source/header pairs

Opened this issue · 0 comments

Add a way to generate source files instead of only header files.

Context (Input, Language)

Input Format:
json schema

Output Language:
C (cJSON)

Description

Header only makes it more complicated and limited in how to use the generated code. C operates with compilation units that end up as object files that are then linked together. Having implementations inside a header file may lead to linkage issues when the same symbols appear in multiple object files.

In general C is typically written with matching *.c and *.h pairs, with all the definitions in the header file, and all the implementations in the source file.

We will improve the quality of the generated code by separating into separate source files and header files:

  • Improve code structure of the generated code
  • Better encapsulation of complexity by keeping the implementations contained in the source files
  • Build cleaner API libraries from the generated code where only the definitions are exposed.

Current Behaviour / Output

Currently Quicktype generates one or more header files containing both definitions and implementations.

Proposed Behaviour / Output

Quicktype should generate header files containing only definitions, and source files containing only implementations.

Solution

The code generator already generate definitions first then proceeds generating implementations. The easiest solution is to close the header file and then open a source file after the definitions have been emitted and before emitting implementations. The source files and header files are usually named the same with different extensions. We can use this and simply replace the .h with .c when creating the corresponding source files.

To avoid changing existing behavior and breaking projects out there I propose to add a command line switch to turn on the generation of source files, leaving the default behavior unchanged.

I have implemented this in a fork and will provide a PR.

Alternatives

The current alternative is to only include the generated header in one source file per project to avoid linkage issues.

Another option is to post process the generated code with external tools, but that is a lot more work and very fragile hack.