Tyler Keeling
Tyler Keeling

Reputation: 13

How to compile a file with compiler directives (`ifdef) and different `define's?

I have two files, file a and file b. File a has compile directives based on whether or not 'b' is defined.

The code in a.sv is as follows:

module a_module()
    initial begin
`ifdef b
            $display("This is compiled in file b");
`else
            $display("This is compiled in file a");
`endif
    end
endmodule: a_module()

The code in b.sv is as follows:

`define b 1
`include a.sv

module b_module()

    a_module a_module();

endmodule: b_module()

Despite defining 'b' before importing file a, running both files will output "This is compiled in file a".

Why is this? How do I structure my code so that a.sv will be independently compiled both times?

Upvotes: 1

Views: 4666

Answers (1)

Serge
Serge

Reputation: 12364

Verilog is different from 'c' in compilation processing. In 'c' every source file is a compilation unit and is self-contained. All macro definition are contained within it.

In verilog all declarations of macros (and all declarations in system verilog global scope) are sticky. This means that macro definitions in one source file are also seen in other source files which follow the one with declarations.

So, in verilog if you want to include the same file with different macro definitions, you would need to employ `define and `undef directives, for example,

`define b
`include "a.sv"
...
`undef b
`include "a.sv"

However, just a note of caution. In real projects this type of inclusions is a source of many errors, incorrect compilations and debugging problems. I suggest that you avoid using it.

Upvotes: 3

Related Questions